为什么不能将使用new创建的对象分配给Java中的通用对象引用?

问题描述 投票:0回答:1

我尝试将使用

new
创建的对象分配给 Java 中的
generic object reference
,如下面给出的代码所示:

interface MyInterface {
    public void myMethod();
}

class MyClass implements MyInterface {
    public void myMethod() {
        System.out.println("Hello World");
    }
}

class MyGeneric<T extends MyInterface> {
    private T obj;

    MyGeneric() {
        this.obj = new MyClass();
    }
    
    MyGeneric(T obj) {
        this.obj = obj;
    }

    public void callMyMethod() {
        obj.myMethod();
    }
}

class Why {
    public static void main(String[] args) {
        MyGeneric<MyClass> mg = new MyGeneric<MyClass>();
        
        mg.callMyMethod();
    }
}

当我尝试使用

javac 17.0.8
编译上面给定的代码时,出现以下错误:

[kunalsharma@fedora ch14]$ javac Why.java 
Why.java:15: error: incompatible types: MyClass cannot be converted to T
        this.obj = new MyClass();
                   ^
  where T is a type-variable:
    T extends MyInterface declared in class MyGeneric
1 error

我尝试用谷歌搜索但没有找到任何答案。 我还在学习 Java,所以我错过了什么吗?

提前致谢。

java generics new-operator
1个回答
0
投票

看起来您遇到了编译错误,因为您试图将

MyClass
的实例直接分配给
T
类中
MyGeneric
类型的字段,并且编译器无法保证
MyClass
是与类型参数兼容
T

要解决此问题,您可以修改

MyGeneric
类的构造函数以接受
T
类型的对象,然后将其分配给
obj
字段。这是修改后的代码:

interface MyInterface {
    public void myMethod();
}

class MyClass implements MyInterface {
    public void myMethod() {
        System.out.println("Hello World");
    }
}

class MyGeneric<T extends MyInterface> {
    private T obj;

    MyGeneric() {
        // You can remove this constructor if not needed
    }

    MyGeneric(T obj) {
        this.obj = obj;
    }

    public void callMyMethod() {
        obj.myMethod();
    }
}

class Why {
    public static void main(String[] args) {
        MyGeneric<MyClass> mg = new MyGeneric<>(new MyClass());
        mg.callMyMethod();
    }
}

在修改后的代码中,

MyGeneric
类现在有一个构造函数,它接受类型为
T
的对象并将其分配给
obj
字段。在
MyGeneric
方法中创建
main
的实例时,您可以将
MyClass
的实例传递给构造函数,它应该可以正常工作,不会出现任何编译错误。

© www.soinside.com 2019 - 2024. All rights reserved.