Understanding class members behavior Polymorphism

אברגיל יעקובו :

I'm facing some difficulties while trying to understand, what actually happens when we initiate an instance of a child class.

public class A { 
2.      public int x, y; 
3.      public A () { x=1; y=2; }
4.      public int getx () { return x; }
5.  }
6.  public class B extends A { 
7.      public int x, z; 
8.      public B () { super(); x=3; y=4; z=5; }
9.      public int getx () { return x; } 
10.     public int getz () { return z; } 
11. }
12. public class Prob1 { 
13.     public static void main (String[] args){
14.         A o1 = new A(); 
15.         A o2 = new B(); 
16.         B o3 = new B();
17.         System.out.println(o1.x);     
18.         System.out.println(o1.getx()); 
19.         System.out.println(o1.y); 
20.         System.out.println(o1.getz()); 
21.         System.out.println(o2.x); 
22.         System.out.println(o2.getx());
23.         System.out.println(o2.y); 

I would love to here a detailed explanation of what is going on here exactly, but the main thing I can't understand is why line '21' prints the number 1, and line '23' prints the number 4.

Eran :

Polymorphism applies to methods, not to instance variables.

Both lines 21 and 23 print the value of the instance variables of class A, since that's the compile time type of o2 (even though its runtime type is B).

21. System.out.println(o2.x); 

The value of A's x member is 1 (set by the constructor public A () { x=1; y=2; }).

23. System.out.println(o2.y); 

The value of A's y member is 4 (set by the constructor public B () { super(); x=3; y=4; z=5; }).

Note the B has an x instance variable that hides A's variable of the same name. Therefore B's constructor doesn't change A's x variable to 3. On the other hand, B doesn't have a y instance variable, so y=4; changes the value of A's y variable to 4.

BTW, line 20 has a compilation error. I had to comment it out in order to execute your code.

Also note that o2.getx() gives a different result than o2.x, since getx() is a method overridden by class B, so it returns B's instance variable x, whose value is 3 (since the runtime type of o2 is B).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=121805&siteId=1