英文:
Implementing Interface and using Class object instead of Interface object
问题
我有接口TestInterface
和类TestClass
。
TestClass
现在实现了这个接口。但是,我想将一个TestClass
对象作为方法的参数传递。
然而,在这里,我收到了一个错误。
为什么会这样?
我以为我可以在任何需要接口对象的地方使用实现了接口的对象。
我该如何更改程序?
public interface TestInterface {
int v = 0;
public void method(TestInterface t);
}
public class TestClass implements TestInterface {
int v = 5;
public void method(TestClass t) {
v = 10;
}
}
英文:
I have the interface TestInterface
and the class TestClass
.
TestClass
now implements this interface. However, I would like to pass a TestClass
object as a parameter for method.
Here, however, an error is displayed to me.
Why is that?
I thought I could use an object that implements the interface wherever an object of the interface can be used.
How do I change the program?
public interface TestInterface {
int v=0;
public void method(TestInterface t);
}
public class TestClass implements TestInterface{
int v = 5;
public void method(TestClass t) {
v=10;
}
}
答案1
得分: 1
You can't do this because that violates the contract of the interface: the method is supposed to accept any implementation of TestInterface
, not specifically instances of TestClass
. Instead, you can use a type parameter in the interface to restrict the parameter types.
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;
}
}
英文:
You can't do this because that violates the contract of the interface: the method is supposed to accept any implementation of TestInterface
, not specifically instances of TestClass
. Instead, you can use a type parameter in the interface to restrict the parameter types.
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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论