Method overriding Vs class variable override in java

I just tried some sample code to test the behavior of overriding a class variable in Java. Below is the code:

class A{
  int i=0;

  void sayHi(){
    System.out.println("Hi From A");
  }
}

 class B extends A{
  int i=2;

  void sayHi(){
    System.out.println("Hi From B");
  }
}


public class HelloWorld {
 public static void main(String[] args) {
    A a= new B();
    System.out.println("i->"+a.i); // this prints 0, which is from A
    System.out.println("i->"+((B)a).i); // this prints 2, which is from B
    a.sayHi(); //  method from B gets called since object is of type B
  }
}

      

I cannot figure out what is going on on these two lines below

System.out.println("i->"+a.i); // this prints 0, which is from A
System.out.println("i->"+((B)a).i); // this prints 2, which is from B

      

Why does it a.i

print 0

even if the object is of type B

? And why is he typing 2

after he has pointed it at B

?

+3


source to share


2 answers


i

is not a method - it is a data item. Items are not overridden, they are hidden . Therefore, even if your instance has B

, it has two data items - i

from A

and i

from B

. When you link to it with a link A

, you get the former, and when you use the link B

(for example, by casting it explicitly), you get the latter.



Instance methods , on the other hand, behave differently. Regardless of the type of reference, since an instance is an instance B

, you will get polymorphic behavior and get a string "Hi From B"

.

+4


source


Even though A is initialized as new B (), the variable is A. if you say

B a = new B();

      



you won't have this problem.

+2


source







All Articles