【问题标题】:Accessing abstract class method访问抽象类方法
【发布时间】:2019-07-09 22:20:47
【问题描述】:

我有三个不同的班级:

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

【问题讨论】:

    标签: java oop inheritance abstract-class


    【解决方案1】:

    java中的覆盖总是基于引用'c'中的目标对象。因此,首先它会在 C 类中为任何可用的 three() 方法的重写版本幸运,否则后续的父类版本将被执行。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        three() 方法在 B 类和 C 类中都被重写

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-26
          相关资源
          最近更新 更多