Reputation: 2274
As per my understanding, when we up cast the child object to the reference of parent class, the child object loses it specific properties pertaining to child class. However, it still recognizes overridden methods and variables.
My question is why the output shows the result from child class in case of over ridden method and result from parent class in case of overridden variables. Why is such difference in behavior among methods and variables
class A
{
int a = 2;
public void show()
{
System.out.println("Inside A");
}
}
class B extends A
{
int a = 555;
void show()
{
System.out.println("Inside B");
}
}
class Demo
{
public static void main(String[] args)
{
A obj = new B();
System.out.println(obj.a); // prints 2.
obj.show(); // prints Inside B
}
}
Upvotes: 0
Views: 78
Reputation: 691715
Because your understanding is wrong. Java objects behave pretty much like real objects. Just because you refer to a Child as a Human doesn't change anything to how the child moves, cries and plays. It's still a Child.
That's the whole point of polymorphism: you can refer to an object without knowing its concrete type, and it will behave as defined in its concrete type definition.
Note that polyporphism and overriding only applies to methods, and not fields. Fields are never resolved in a polymorphic way. They should not be accessed directly from the outside anyway: always through methods. That's the other main principle of OO: encapsulation.
In B, you're not overriding the field a, but introducing another field with the same name, which hides the one defined in A.
Upvotes: 1