繁体   English   中英

java 通用构造函数未定义

[英]java Generic constructor undefined

我正在学习 java 和 generics 并遇到了一些问题。 我已阅读 Stackoverflow 上发布的有关泛型的所有问题,但不明白为什么会发生此错误

class Student{

    String name;
    float marks;

    Student(String name,float marks){
        this.name = name;
        this.marks = marks;
    }

}

public class GenericClassEx<T> {
    
    T obj;
        GenericClassEx(T data){
       
        this.obj = data;
    }

    public T getObject(){
        return this.obj;
    }

    public static void main(String[] args) {
        Float d = new Float(10);
        GenericClassEx<Student> iobj= new GenericClassEx <Student> ("prince",d);
        System.out.println(iobj.getObject());
    }

}

当我运行这段代码时,它说

GenericClassEx.java:28: error: constructor GenericClassEx in class GenericClassEx<T> cannot be applied to given types;
        GenericClassEx<Student> iobj= new GenericClassEx <Student> ("prince",d);
                                      ^
  required: Student
  found: String,Float
  reason: actual and formal argument lists differ in length
  where T is a type-variable:
    T extends Object declared in class GenericClassEx
Note: GenericClassEx.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error

您需要将Student的 object 传递给构造函数GenericClassEx(T data) 取而代之的是,您将两个 arguments、 "prince"d传递给它。

代替

GenericClassEx<Student> iobj= new GenericClassEx <Student> ("prince",d);

GenericClassEx<Student> iobj = new GenericClassEx<Student>(new Student("prince", d));

附带说明一下,构造函数Float(double value)自 Java-9 以来已被弃用。

代替

Float d = new Float(10);

Float d = Float.valueOf(10);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM