问题
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