Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 实现接口并使用类对象代替接口对象_Java - Fatal编程技术网

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;   
    }
}