实现接口并使用类对象而不是接口对象

huangapple go评论75阅读模式
英文:

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&lt;T extends TestInterface&lt;T&gt;&gt; {
    int v=0;
    public void method(T t);
}
public class TestClass implements TestInterface&lt;TestClass&gt;{
    int v = 5;
    public void method(TestClass t) {
        v=10;   
    }
}

huangapple
  • 本文由 发表于 2020年8月7日 02:08:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63289400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定