-1

I have a subclass object. Can I access a hidden variable of the superclass without using the super keyword. ?? Actually, I found a technique.. Its working but I don't understand the conceptual reason behind it.

class A {
    public int a = 5; 
    private int c = 6; 

    void superclass() {
        System.out.println("Super class" + " " + "value of a is " + a);
        System.out.println("Super class" + " " + "value of c is " + c);
    }
}

class B extends A {
   int b = 7;
   int a = 8; 

   void subclass() {
       System.out.println("Sub class" + " " + "value of b is " + b);
       System.out.println("Sub class" + " " + "value of a is " + a);
   }
}

class Demo {
    public static void main(String args[]) {
       A a1 = new A();
       B b1 = new B();

       b1.superclass();
   }
}

In the above code, if b1 is a object of class B.I have called a superclass method named superclass(); Now the output is a=5. But my argument is why can't it be a=8 ? a=5 is hidden and to access it, we have to use super keyword. But here without super key word I am getting a=5. How can it be possible?

Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33

2 Answers2

2

Fields are not overriden.

So even though B defines an int named 'a' and A defines the same int with the same name does not mean they are the same field.

What is seen here is Encapsulation. Accessing fields through a controlled method (here, superclass()). When you call superclass, it looks for the field a, which is within its own class. The class A knows nothing about the field a in B, not even that it exists.

There is also another SnackOverflow question here on this: If you override a field in a subclass of a class, the subclass has two fields with the same name(and different type)?

Community
  • 1
  • 1
Obicere
  • 2,999
  • 3
  • 20
  • 31
0

In this case, when you call a method of the superclass, irrespective of which class extends it, it will print the value that is in the class. This is because the superclass does not know which (or how many classes) extend it. That is the basic OOP principle of encapsulation.

Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33