从父类方法调用子类方法

Kau*_*mar 7 java oop methods inheritance

考虑以下情况

class A
{
    X()
    {
        //some code
        Y();
    }
}

class B extends A
{
    Y(){ //some code }
}
Run Code Online (Sandbox Code Playgroud)

如果我创建了一个类的对象B,并且我尝试使用X从它扩展而来A的函数,那么该函数是否有可能X访问Y类的调用对象的函数B

ΦXo*_*a ツ 8

你可以,但这必须满足

  1. 一个类是抽象的
  2. Y 方法也是抽象的

例子:

abstract class A {
    void X() {
        Y();
    }

    abstract void Y();
}

class B extends A {
    @Override
    void Y() {
        System.out.println("Hello from B class");
    }
}
Run Code Online (Sandbox Code Playgroud)

以这种形式,每次类 A 调用 Y 时,它实际上都会调用抽象方法 Y 的实现方法