Java:扩展类并实现具有相同方法的接口 [英] Java: extending a class and implementing an interface that have the same method
本文介绍了Java:扩展类并实现具有相同方法的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能无法完成以下操作(我收到编译错误:继承的方法 A.doSomthing(int) 无法隐藏 B 中的公共抽象方法"):
Probably the following cannot be done (I am getting a compilation error: "The inherited method A.doSomthing(int) cannot hide the public abstract method in B"):
public class A {
int doSomthing(int x) {
return x;
}
}
public interface B {
int doSomthing(int x);
}
public class C extends A implements B {
//trying to override doSomthing...
int doSomthing(int x) {
return doSomthingElse(x);
}
}
假设我既不能改变 A 也不能改变 B,我的问题是我能不能以某种方式定义 C,使其同时继承 A 和 B(假设某些框架要求 C 既是一个A 和 B 的实例).
Assuming I am allowed to change neither A nor B, my question is can I somehow define C in such a way that it will inherit from both A and B (suppose that it is required for some framework that C will be both an instance of A and B).
否则,您将如何解决此问题?
Or if not, how would you work around this?
谢谢!
推荐答案
公开方法
public class C extends A implements B {
//trying to override doSomthing...
public int myMethod(int x) {
return doSomthingElse(x);
}
}
接口方法总是public
或者只是使用组合而不是继承
or just use composition instead of inheritance
这篇关于Java:扩展类并实现具有相同方法的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文