interface Test {
Object print();
}
class Test1 implements Test {
public Object print() {
System.out.print("print interface");
return new Test1();
}
}
public class E {
public static void main(String[] args) {
Test1 t1 = new Test1();
Test1 t2 = t1.print();
}
}
这里的print方法在Test1类中实现了一个新的test1对象t1被创建并使用这个对象的print方法被调用,返回test1类的对象,但我不明白为什么它会给出编译错误
incompatible types: Object cannot be converted to Test1
Test1 t2=t1.print();
答案 0 :(得分:1)
print()
方法的返回类型为Object
,而非Test1
。由于编译器不会知道您实际上正在返回Test1
的实例,因此会抛出错误。
将print()
的返回类型更改为Test
,将t2
的类型更改为Test
,或将t2
的类型更改为Object
}。
答案 1 :(得分:1)
考虑这一行,
Test1 t2 = t1.print();//wrong code
在这种情况下你必须明确地进行类型转换。
Test1 t2 = (Test1)t1.print();//correct code
如果缩小转换(父类--->子类),则必须明确进行类型转换 您的编译器会自动在扩展转换中进行类型转换(Child class ---> Parent class)。
答案 2 :(得分:0)
Java是一种静态检查语言,如果在编译时无法确定您的代码是否正确,它将给您一个编译错误。
Test1 t2=t1.print();
与
相同Object tmp = t1.print();
Test1 t2 = tmp; // this is a compiler error as it doesn't know the Object is a Test1
您如何使用它并不意味着在这种情况下它不再是编译错误。
更好的选择是使用协变返回类型。
public Test1 print() {
System.out.print("print interface");
return new Test1();
}
注意:Test1.print
具有更具体的返回类型,并明确表示它将是Test1
BTW您可以使用泛型
将其转换为运行时问题interface Test {
<T> T print();
}
class Test1 implements Test {
public <T> T print() {
System.out.print("print interface");
return (T) new Test1();// you get a warning here but it compiles
}
}
public class E {
public static void main(String[] args) {
Test1 t1 = new Test1();
Test1 t2 = t1.print(); // the compiler assumes the right type will be returned
}
}
答案 3 :(得分:0)
我认为@PeterLawrey&#34; BTW&#34;只是通过添加在运行时失败的可能性来增加不必要的混淆。
如果您希望能够从Test.print
方法返回实现类型,则可以在接口上定义类型变量,而不是在方法上:
interface Test<T> {
T print();
}
class Test1 implements Test<Test1> {
@Override public Test1 print() {
// ...
return new Test1();
}
}
现在,如果您不使用原始类型或其他内容来破坏泛型,则不会收到任何警告,并且您不会遇到任何潜在的运行时故障。
答案 4 :(得分:0)
尝试使用它来施展它:
Test1 t2 = (Test1)t1.print();