As I can understand here 'a1' reffed to a class B object which has 'a=200' as an attribute. Therefore I expected program will print 200. But why does this program prints 100 instead of 200?
class A{
int a=100;
}
class B extends A{
int a=200;
}
class Demo{
public static void main(String args[]){
A a1=new B();
System.out.println("a : "+a1.a); //Prints 100
}
}
By declaring a field in class B that has the same name as a field in its parent class A, you are essentially hiding that field. However, field access on a variable is done based on that variable's declared/static type.
In other words, fields are not polymorphic entities like methods are.
In this case, the variable a1 is declared as type A. The field accessed will therefore be the one in the parent class, A.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With