首页 > 解决方案 > 访问抽象类方法

问题描述

我有三个不同的课程:

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 类中运行三个。

标签: javaoopinheritanceabstract-class

解决方案


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

由于 c 是 C 类的一个实例,任何对 c 对象的 three() 方法的引用都会调用 C 类中的 three() 实现


推荐阅读