Java继承:为什么在父构造函数级别调用方法,调用重写的子方法? [英] Java Inheritance: Why calling a method at the parent constructor level, calls the overridden child method?
问题描述
调用Fruit构造函数中的fruitName方法,实际上是将调用委托给子类Apple类的方法!
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());
}
}
这背后的主要尝试是,我试图调用父方法而不使用在子方法中调用super.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.
请帮助我@line#12
Please help me @line #12
推荐答案
这是多态101.最具体的 - 即继承树上的最低 - 方法的版本是在类层次结构中调用。如果你没有覆盖所有的fruitName()方法,那么将调用基类方法。
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.
这篇关于Java继承:为什么在父构造函数级别调用方法,调用重写的子方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!