[英]Accessing abstract class method
我有三个不同的类:
1-)
abstract class A {
abstract void one();
void two(){
System.out.println("two");
one();
}
abstract void three();
}
2-)
abstract class B extends A {
void one() {
System.out.println("one");
three();//I think this method has to run
}
void three() {
System.out.println("3");//That
}
}
3-)
public class C extends B {
void three(){
System.out.println("three");
}
}
在 Main 方法中
public static void main(String [] args){
C c=new C();
c.one();
c.two();
c.three();
}
输出 :
one
three
two
one
three
three
但是我认为在第二个代码中 one() 方法必须运行它的三个方法并且它必须显示“3”而不是“三个”但是这个代码在 C 类中运行三个。
三()方法在 B 和 C 类中都被覆盖
由于 c 是 C 类的实例,任何对带有 c 对象的three() 方法的引用都将调用C 类中的three() 实现
three()
方法在C
被覆盖。 由于c
持有C
的实例,这就是您看到的输出。
java 中的覆盖始终基于引用“c”中的目标对象。 因此,首先它会在 C 类中为任何可用的三()方法覆盖版本运气好,否则将执行后续的父类版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.