访问抽象类方法



我有三个不同的类:

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");
}
}

在主要方法中

public static void main(String [] args){
C c=new C();
c.one();
c.two();
c.three();
}

输出:

one
three
two
one
three
three

,但我认为在第二个代码中必须运行其三种方法,并且必须显示" 3"而不是"三",但此代码在C类中运行三个。

三()方法在B和C类中都被覆盖

由于C是C类的实例,因此使用C对象对三个()方法的任何引用都会在C类中调用三()实现

three()方法在C中被覆盖。由于c拥有C的实例,这就是您看到的输出。

在Java中覆盖总是根据参考'c'中的目标对象起作用。因此,首先,它将在C类中查找三个()方法的任何可用覆盖版本,否则,随后的父级版本将被执行。

最新更新