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?
 
     
    