Issue
I tried to assign object created with new to generic object reference in Java as in code given below:
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();
}
}
when I tried to compile above given code using javac 17.0.8 I got following error:
[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
I tried googling it but didn't found any answer. I am still learning Java so Am I missing something?
Thanks in Advance.
Solution
It looks like you are encountering a compilation error because you are trying to assign an instance of MyClass directly to a field of type T within the MyGeneric class, and the compiler is unable to guarantee that MyClass is compatible with the type parameter T.
To fix this issue, you can modify the constructor of the MyGeneric class to accept an object of type T and then assign it to the obj field. Here's the modified code:
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();
}
}
In the modified code, the MyGeneric class now has a constructor that takes an object of type T and assigns it to the obj field. When creating an instance of MyGeneric in the main method, you can pass an instance of MyClass to the constructor, and it should work without any compilation errors.
Answered By - justinbitter
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.