在调用继承方法时,子类是否会使用超类或子类方法(Java)

Jan*_*ser 0 java inheritance

如果我在超类中有两个方法,则将它们称为a()和b(),并且b()调用a(),并且我有一个子类覆盖a(),然后,如果我在一个实例上调用b()在子类中,它会使用超类中的a()变体还是子类中的变体?

提前感谢任何答案:我没有找到任何搜索内容,因为这个问题很难用作搜索词.

Nay*_*uki 5

它将调用子类中的那个.您可以设计一个实验来自己测试:

class Super {
    void a() { System.out.println("super implementation"); }
    void b() { System.out.println("calling a()..."); a(); }
}


class Sub extends Super {
    void a() { System.out.println("sub implementation"); }
}


public class Main {
    public static void main(String[] args) {
        Sub x = new Sub();
        x.b();
        // Prints:
        //   calling a()...
        //   sub implementation
    }
}
Run Code Online (Sandbox Code Playgroud)