3

I was just trying some sample code for checking class variable overriding behavior 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 am not able to understand whats happening at 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 a.i print 0 even if the object is of type B? And why does it print 2 after casting it to B?

Amit.rk3
  • 2,417
  • 2
  • 10
  • 16
  • if you want to override class variable then look at this http://stackoverflow.com/a/28263825/4726707 – Blip May 31 '15 at 14:46
  • Thanks mate. I was aware of how to do it. But I was looking more into the root cause and why it happens. Got my answer below. – Amit.rk3 May 31 '15 at 14:52

2 Answers2

4

i is not a method - it's a data member. Data members don't override, they hide. So even though your instance is a B, it has two data members - i from A and i from B. When you reference it through an A reference you will get the former and when you use a B reference (e.g., by explicitly casting it), you'll get the latter.

Instance methods, on the other hand, behave differently. Regardless of the the type of the reference, since the instance is a B instance, you'll get the polymorphic behavior and get the string "Hi From B" printed.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

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

B a = new B();

you won't have that problem.

canoe123
  • 21
  • 3