-3

I am having following classes

public class InheritTest{
    Parent p = new Child();
    Child c = (Child)p;
    void someMethod(){
        System.out.println(p.getX()+" "+c.getX());
    }
    public static void main (String [] args){
        InheritTest it = new InheritTest();
        it.someMethod();
    }

    class Child extends Parent{
         int x = 1;
        int getX(){
            return this.x;
        }
    }

}

And

public class Parent{
    int x = 0;
    int getX(){
        return x;
    }
}

When I call, p.getX() and c.getX(), it prints 1 & 1

but when I call p.x and c.x, it prints 0 & 1

how this multi-level inheritance works ? Please help me understand this.

rijndael
  • 101
  • 4

1 Answers1

1
  • In the line Parent p = new Child(); you create p as a reference to an object of type Child
  • Then you create c as a second reference to the same object

The object is the object. It is what it is. It is a Child.

A reference has a type, and an object has a type. They are not the same thing. They do have to be compatible.

  • The type of p is Parent
  • The type of c is Child
  • The type of the object is Child, regardless of which reference (p or c) you are using

With regard to the different in behaviour overriding between a method and a field, see:

Community
  • 1
  • 1
Stewart
  • 17,616
  • 8
  • 52
  • 80