有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java泛型与使用参数化类有关

全部!我已经为这件事伤心了好几个小时了。如果这是一件很琐碎的事情,我很抱歉,但我想我对Java泛型的理解还不够透彻。我是一名Java程序员新手

我有两个接口。Int1和Int2。Int2扩展了Int1。Int2Impl实现Int2。第1课。java和其他类。下面也给出了java。课后提问

Int1。爪哇

     public interface Int1<E> {
           public Lesson1<E> interfaceimpl(Class<E> klass);
     }

Int2。爪哇

     public interface Int2<E> extends Int1<E> {
         String getSomething();
     }

第1课。爪哇

    public class Lesson1<E> {

    }

Int2Impl。爪哇

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

另一班。爪哇

  public class AnotherClass<E> {
        private Int2<E> interface2; 

        private <E> void newMethod(Class<E> klass) {
            interface2 = new Int2Impl<>();
          **interface2.interfaceimpl(klass);**

      }
   }

导致编译问题的代码行是

接口2。接口接口(klass);在另一节课上。爪哇

Eclipse提供的错误和快速修复包括:

错误:

  The method interfaceimpl(java.lang.Class<E>) in the type Int1<E> is not 
  applicable for the arguments (java.lang.Class<E>)

快速修复:

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'

这些速效药对我来说毫无意义。另外,无论我选择哪一个,他们也不会解决问题。谁能 指出错误以及Eclipse抛出此错误的原因

谢谢


共 (1) 个答案

  1. # 1 楼答案

    您的AnotherClass已经是泛型类型E。无需在方法级别再次定义E

    只需从newMethod()中删除<E>,如下所示:

    public class AnotherClass<E> {
        private Int2<E> interface2;
    
        private void newMethod(Class<E> klass) {
            interface2 = new Int2Impl<>();
            interface2.interfaceimpl(klass);
    
        }
    }