繁体   English   中英

接口和类中的方法签名相同

[英]same method signature in interface and class

interface TestInterface {
    void work();
}

class TestClass {
    public void work(){
        System.out.println("Work in CLASS");
    }
}

public class Driver extends TestClass implements TestInterface {
    public static void main(String[] args) {
        new TestClass().work();
    }
}

谁能向我解释一下,为什么只因为在TestClass中存在相同的工作方法签名,所以该类编译良好?

实现接口的要求是该类提供接口指定的所有方法的实现。 Driver提供work()的必需实现,因为它从TestClass继承了一个完全匹配的方法。 因此它可以用作TestInterface的实现。

这是因为接口的所有方法都已实现。 这是在实现类中省略@Override注释的同一原因(这不是一个好习惯,因为方法签名可能会更改,并且您可能会无意中使用其他一些公共方法来实现更改的方法)。

但是,您的构造是不稳定的,因为您依赖于TestClass,而TestClass并不知道您要签名实现的接口

暂无
暂无

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

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