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
This is because methods in Java are overridden when redefined in a child class, but attributes are shadowed. Thus there will only be one method shout()
available, but there are two actual attributes i.
In a real case scenario, you would probably define your attributes private if you would need to use the same name. Then you would explicitly handle to choose which one you want to access using getters (like shout()
that pretty much is a getter for i). Or at least explicitly point out what i by casting to the right class. If you still want to shadow a public attribute with another having the same name, you can still refer to them as super.i
or this.i
to select the right one.