-3

When an instance variable that is present in parent class is also defined in a child class , is it not inheriting the instance variable?

class ClassA {
    int a = 20;

    public int getA() {
        return a; 
    }
}

class ClassB extends ClassA {
    int a=30;

    ClassB(int a) {
        this.a = a;
    }
}

class TestInheritance {
    public static void main(String args[]) {
        ClassA instanceA = new ClassB(50);
        System.out.println(instanceA.getA());
    }
}

Output:

20

Please explain the output of the above program.

Pankaj
  • 14,638
  • 3
  • 17
  • 23
  • possible duplicate of [Hidden fields though inheritance](http://stackoverflow.com/questions/8647248/hidden-fields-though-inheritance) – Tom May 30 '15 at 08:18

2 Answers2

2

No. Instance variables are not overridden in the same way as methods. In this example, an object whose class is ClassB actually has two instance variables called a - the one declared in ClassA and the one declared in ClassB. Any code written in ClassA will access the one declared in ClassA, and any code written in ClassB will access the one declared in ClassB.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • Thanks David. When you say ClassB object has two instance variable does that mean when an object of ClassB is created then it will have all the inheritable instance variable of its parent ClassA and its own instance variable. But the instance variable in ClassA with same name as its instance variables are not accessible through reference of ClassB. – Pankaj Jun 01 '15 at 06:46
2

In Java, if a parent class and a child class have a field with the same name, the field doesn't override the parent's field.

When the compiler has to decide which field to use - the one declared in the parent or the one in the child - it does so based on the type of the reference variable being used. So, if you declared

ClassA instanceA;

Then whatever you assign to instanceA, whether a real ClassA or any child - if you write instanceA.a, it means "the a that was declared in ClassA". If you declared:

ClassB instanceB;

Then whatever you assign to instanceB (suppose, ClassB also has children), the compiler will treat instanceB.a as "the a that was declared in ClassB".

But the field is inherited, even if it is not overridden. That is, if you remove the declaration from ClassB, then the compiler takes instanceB.a to mean "the field a that ClassB inherited from ClassA".

The term used for a field in a child class that has the same name as a field in a parent class is hiding (which is distinct from shadowing and obscuring - terms that are also used for certain situations in which the same name is used for two different items).

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79