Reputation: 1142
All! I have breaking my head over this things for a few hours now. I'm sorry if it's something so trivial but I guess I don't understand Java generics well enough. I'm a novice Java programmer.
I have 2 interfaces. Int1 and Int2. Int2 extends Int1. Int2Impl implements Int2. Lesson1.java and AnotherClass.java are given below also. Questions follow after the classes.
Int1.java
public interface Int1<E> {
public Lesson1<E> interfaceimpl(Class<E> klass);
}
Int2.java
public interface Int2<E> extends Int1<E> {
String getSomething();
}
Lesson1.java
public class Lesson1<E> {
}
Int2Impl.java
public class Int2Impl<E> implements Int2<E> {
Class<E> klass;
@Override
public String getSomething() {
return "nothing";
}
@Override
public Lesson1<E> interfaceimpl(Class<E> klass) {
this.klass = klass;
return null;
}
}
AnotherClass.java
public class AnotherClass<E> {
private Int2<E> interface2;
private <E> void newMethod(Class<E> klass) {
interface2 = new Int2Impl<>();
**interface2.interfaceimpl(klass);**
}
}
The line of code that's causing a compilation issue is,
interface2.interfaceimpl(klass); in the class AnotherClass.java
the errors and the quickfixes that Eclipse offers are:
Error:
The method interfaceimpl(java.lang.Class<E>) in the type Int1<E> is not
applicable for the arguments (java.lang.Class<E>)
Quick Fixes:
1) Change method interfaceImpl(Class<E>) to interface(Class<E>)
2) Cast Argument klass to Class<E>
3) Change type of klass to Class<E>
4) Create method interfaceImpl(Class<E>) in type 'Int2'
None of the quick fixes make sense to me. Plus they also don't fix the problem regardless of which one I choose. Can someone point out the mistake and why Eclipse throws this error?
Thanks!
Upvotes: 0
Views: 58
Reputation: 8606
Your AnotherClass
is already of generic type E
. No need to define E
again at method level.
Just remove <E>
from your newMethod()
as follows:
public class AnotherClass<E> {
private Int2<E> interface2;
private void newMethod(Class<E> klass) {
interface2 = new Int2Impl<>();
interface2.interfaceimpl(klass);
}
}
Upvotes: 4