Java Inheritance: Why calling a method at the parent constructor level, calls the overridden child method?

杀马特。学长 韩版系。学妹 提交于 2019-12-23 04:13:04

问题


Calling the fruitName method inside Fruit constructor, is actually delegating the call to the child Apple class's method!

public class CallingParentMethodInInheritanceHierarchy {

abstract class Fruit {
    String fruitName;

    public Fruit(String fruitName) {
        this.fruitName = fruitName;

        /*
         * o/p - Inside constructor - Child: Fruit name is - Apple
         */
        System.out.println("Inside constructor - " + fruitName()); // doubt?
    }

    public String fruitName() {
        return "Parent: Fruit name is - " + fruitName;
    }

    public abstract String type();

}

class Apple extends Fruit {
    public Apple() {
        super("Apple");
    }

    public String fruitName() {
        /*
         * To call the super class method, only way is -
         * 
         * System.out.println(super.fruitName());
         */
        return "Child: Fruit name is - " + fruitName;
    }

    @Override
    public String type() {
        return "AllSeasonsFruit";
    }
}

public static void main(String[] args) {
    Fruit fruit = new CallingParentMethodInInheritanceHierarchy().new Apple();

    /*
     * o/p - Child: Fruit name is - Apple
     */
    System.out.println(fruit.fruitName());
}

}

The main attempt behind this, is that I was trying to call the parent method without using the trivial way super.fruitName() call inside a child method.

Please help me @line #12


回答1:


This is polymorphism 101. The most specific - i.e. lowest on the inheritance tree - version of a method is invoked within a class hierarchy. If you had not overridden the fruitName() method at all then the base class method would be called.




回答2:


Because that's how polymorphism works. Child classes can override any method that is not final, and parent code won't be able to tell the difference. That's why non-abstract non-final public methods are generally discouraged.



来源:https://stackoverflow.com/questions/33845392/java-inheritance-why-calling-a-method-at-the-parent-constructor-level-calls-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!