Java 实现接口并使用类对象代替接口对象
我有接口Java 实现接口并使用类对象代替接口对象,java,Java,我有接口TestInterface和类TestClass TestClass现在实现这个接口。然而,我想传递一个TestClass对象作为方法的参数 然而,这里向我显示了一个错误 为什么呢 我想我可以在任何可以使用接口对象的地方使用一个实现接口的对象 如何更改程序 public interface TestInterface { int v=0; public void method(TestInterface t); } 您不能这样做,因为这违反了接口的约定:该方法应该接受T
TestInterface
和类TestClass
TestClass
现在实现这个接口。然而,我想传递一个TestClass
对象作为方法的参数
然而,这里向我显示了一个错误
为什么呢
我想我可以在任何可以使用接口对象的地方使用一个实现接口的对象
如何更改程序
public interface TestInterface {
int v=0;
public void method(TestInterface t);
}
您不能这样做,因为这违反了接口的约定:该方法应该接受
TestInterface
的任何实现,而不是TestClass
的具体实例。相反,您可以在接口中使用类型参数来限制参数类型
public interface TestInterface<T extends TestInterface<T>> {
int v=0;
public void method(T t);
}
public class TestClass implements TestInterface<TestClass>{
int v = 5;
public void method(TestClass t) {
v=10;
}
}
公共接口测试界面{
int v=0;
公共无效法(T);
}
公共类TestClass实现TestInterface{
int v=5;
公共void方法(TestClass t){
v=10;
}
}
您遇到了什么具体错误?(根本原因可能是混淆了不能在接口中定义变量——或者,可以,但它们并没有达到预期的效果——但适当的修复将取决于确切的错误。)重写方法时,不能使参数的类型更具体。想象一个场景(假设编译没有错误),其中您有一个TestInterface
类型的变量foo
(实际上是一个TestClass
)和另一个TestInterface
对象bar
(它不是TestClass
实例)并调用foo.method(bar)
。您的代码将无法工作,因为TestClass的方法
需要一个TestClass
,即使TestInterface
适用于任何TestInterface
也请注意,您只能在接口中生成静态变量,即使TestInterface
是一个类,来自超类的v
将被遮挡。
public interface TestInterface<T extends TestInterface<T>> {
int v=0;
public void method(T t);
}
public class TestClass implements TestInterface<TestClass>{
int v = 5;
public void method(TestClass t) {
v=10;
}
}