繁体   English   中英

子类在调用继承的方法(Java)时会使用父类还是子类方法

[英]Will a subclass use a super or sub class method when calling an inherited method (Java)

如果我在超类中有两个方法,则将它们分别称为a()和b(),而b()则调用a(),并且我有一个子类重写了a(),那么,如果我在实例上调用b()子类,它将使用超类中a()的变体还是子类中的a()?

预先感谢您提供任何答案:我在搜索中没有发现任何问题,因为该问题很难用短语来表达。

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

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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM