In the code given below when we are trying to initiate object of type A by calling the constructor of a child class when we print x.i java refers to the parent class attribute and why when called through a method it refers to a child class attribute, I am unable to clearly understand how upcast is working here.
Following is the code:
public class Main
{
public static void main(String[] args) {
A x = new B();
System.out.println(x.i);
System.out.println(x.shout());
}
}
class A{
int i = 10;
int shout(){
return i;
}
}
class B extends A{
int i = 20;
int shout(){
return i;
}
}
Following is the output: 10 20