0

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!

1
  • 2
    remove <E> from the newMethod? private void newMethod(Class<E> klass) { interface2 = new Int2Impl<>(); interface2.interfaceimpl(klass); } Commented Mar 24, 2018 at 7:49

1 Answer 1

4

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

    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Well spotted +1
Thanks @sfat! that fixed it! :-)
glad I could help. Happy coding and a nice weekend! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.