Malwaregeek
Malwaregeek

Reputation: 2274

Difference when overridden variable and method from child class are accessed

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

Answers (2)

JB Nizet
JB Nizet

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

sanbhat
sanbhat

Reputation: 17622

Overriding applies to methods, not fields. Having same field in subclass hides the super class field.

Since type of obj is A, the actual value a which is intialized in A gets printed

Upvotes: 0

Related Questions