如果我在超类中有两个方法,调用它们a()和b(), b()调用a(),并且我有一个覆盖a()的子类,那么,如果我在子类的实例上调用b(),它会在超类中使用a()的变体还是在子类中使用?
提前感谢任何答案:我没有找到任何搜索,因为这个问题很难作为一个搜索词来表达。
它将调用子类中的一个。你可以为自己设计一个实验来测试:
class Super {
void a() { System.out.println("super implementation"); }
void b() { System.out.println("calling a()..."); a(); }
}
class Sub extends Super {
void a() { System.out.println("sub implementation"); }
}
public class Main {
public static void main(String[] args) {
Sub x = new Sub();
x.b();
// Prints:
// calling a()...
// sub implementation
}
}