![](/img/trans.png)
[英]Implementing and extending, Interface and Abstract class respectively with same method name in java
[英]Extending a non abstract class and implementing an interface with same method signatures in a class
我有以下类和接口
public class A {
public void printSomething() {
System.out.println("printing from A");
}
}
interface B {
public void printSomething();
}
public class C extends A implements B {
public static void main(String aa[]) {
C c = new C();
c.printSomething();
}
}
当我编译上面的代码时,它编译没有任何错误。 当我运行程序时,它会打印以下内容。
printing from A
我期望编译器给出类似的错误,例如当我的类C 没有扩展类A时遇到的以下错误
C.java:1: error: C is not abstract and does not override abstract method printSomething() in B public class C implements B{
^
C.java:8: error: cannot find symbol
c.printSomething();
^
symbol: method printSomething()
location: variable c of type C
2 errors
我知道当类实现接口时,我们需要在类中定义接口方法或声明类抽象。 但是,仅通过扩展类(具有相同签名的已定义方法),如何能够克服此编译器警告并运行程序。
这样做绝对好,而且非常普遍。
您正在使用class A
作为实施的工具interface
由指定interface B
。
这种模式有助于模块化和潜在的代码重用。
这是因为C是A的子级。每当执行子级默认承包商时,都会调用其父构造函数(这将继承A的所有属性)。 在这种情况下,“ new C()”使A()的所有属性对类C都可用,包括printSomething()。
这是因为,通过将class A
扩展为class C
,您实际上为interface B
的printSomething()
方法提供了实现。
请注意: class A
包含printSomething()
方法的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.