Hi Chuan Chung Tsao
Following is a modified version of your program so as to make u understand logic well.......
class A
{int i = 10;
public void m()
{System.out.println("In m() of Super Class");}
}
public class B extends A
{int i = 20;
public void m()
{System.out.println("In m() of Sub Class");}
public static void main(String[] args)
{ A a = new A();
System.out.println("value of i :: "+a.i);
a.m();
}
}
1>
A a = new A();
value of i :: 10
In m() of Super Class
Logic :: Instance of Superclass A is created and thus variable and method of superclass are accessed.
*********************************************
2>
A a = new B();
value of i :: 10
In m() of Sub Class
Logic ::
Dynamic Method dispatch is what is happening here.
Instance created is of type Class A but is pointing towards Class B. As a result of which method of class B ie subclass is accessed.
Variable accessed however of superclass as variables are not overrided in case Dynamic Method dispatch.
*********************************************
3>
B a = new B();
value of i :: 20
In m() of Sub Class
Logic :: Instance of Subclass B is created and thus variable and method of subclass are accessed.
*********************************************
4>
B a = new A();
Compile Time Error :: Incompatible types
B a = new A();
Logic :: Casting is required.
Solution -> B a = (B) new A();
This however will again cause ClassCast Excetion as instance of Superclass can not be casted to instance of Subclass. Converse however is correct.
Hope this clarifies your doubt ... In case u need more information just let me know....