-1
class Main{
    public static void main(String args[]){
        A ob = new B();
        System.out.println(ob.x);   
    }
}
class A{
    int x;
    public A(){
    x = 10;
    }
}
class B extends A{
    int x;
    public B(){
    x = 20;
    }
}

The output of the code is 10. I don't understand how this works. And why isn't B ob = new A() valid? Also is there any real-world use of this?

Aditya
  • 19
  • 1
  • 1
    Does this answer your question? ["Program to an interface". What does it mean?](https://stackoverflow.com/questions/1992384/program-to-an-interface-what-does-it-mean) – Guy Jan 12 '20 at 12:04
  • `A ob = new B()` is valid because all Bs are also As, that's what inheritance means. `B ob = new A()` isn't valid because not all As are Bs. – jonrsharpe Jan 12 '20 at 12:19
  • Does this answer your question? [Why can't reference to child Class object refer to the parent Class object?](https://stackoverflow.com/questions/2145767/why-cant-reference-to-child-class-object-refer-to-the-parent-class-object) – Devkinandan Chauhan Jan 13 '20 at 05:09

1 Answers1

1

If a parent reference variable is holding the reference of the child class and we have the “value” variable in both the parent and child class, it will refer to the parent class “value” variable, whether it is holding child class object reference.

The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class because the compiler uses a special run-time polymorphism mechanism only for methods.

Please refer: Parent Child class having Same data member

Every Child is a Parent but not every Parent is a Child.

Please refer: Child cannot refer Parent

Devkinandan Chauhan
  • 1,785
  • 1
  • 17
  • 42