Home > Software design >  Java child object stored in parent variable. why it's calling child method instead of calling t
Java child object stored in parent variable. why it's calling child method instead of calling t

Time:09-17

class Mom{
    public String sex(){
        return "Female";
    }
}
class Son extends Mom{
    @Override
    public String sex(){
        return "Male";
    }
}

Mom mom=new Son();

Now why mom.sex() returning "Male" should it not return "Female". I'm confused.

Because according to my thinking.It's overriden in child class logic.Shouldn't it act as the parent class logic in this context?

CodePudding user response:

When you run Mom obj = new John();, then you have created a new John instance. A John can also be used as a Mom because that's its super class, but when you call methods on it, they are still called on your John instance, where in your case you've overridden the sex method which's original implementation is in Mom.

CodePudding user response:

Once you have overridden the method in child class, the implementation of child class will get higher priority over parent class. That is how Override works. If you remove the overridden implementation then parent class i.e. Mom implementation will be triggered.

Remember left hand side of = shows the type of object whereas right hand side of = represents the concrete implementation.

  • Related