Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confused in Inheritance, could anyone help me? [duplicate]

Tags:

java

Code in Java

public class A {
    int x;

    public A() {
       x = 0;
    }

    public void print() {
        System.out.println("This is A");
    }
}

public class B extends A {
     int x;

     public B() {
        x = 1;
     }

     public void print() {
         System.out.println("This is B");
     }
}

B b = new B();
A a = b;

System.out.print(a.x);---------------->0 
a.print();---------------->This is B

I am very confused. I create object b for B class, although I assign b to a, I think b should still point the class B. Why the "a.x" will return 0 instead of 1? Why a.x point to the x in A, but a.print() point to the print() method in B?

like image 351
aminy Avatar asked Dec 13 '25 17:12

aminy


2 Answers

fields are not polymorphic but the methods are,

which means method will be invoked on the object which is referred by reference at runtime

field variables are tied to reference, so if you remove field x from class A and try the same code it will fail to compile

like image 50
jmj Avatar answered Dec 15 '25 09:12

jmj


You are seeing some irregularities on how polymorphism is applied in Java. Polymorphism is seen where invoking a.print() invokes B's print(), while this is not the case for fields. The field is tied to the reference, so in this case b.x and a.x are distinct (although you could leave out x in B's definition and have a single field declared in the superclass. In that case, a form of hiding is seen.

like image 30
nanofarad Avatar answered Dec 15 '25 09:12

nanofarad