简体   繁体   English

java 通用构造函数未定义

[英]java Generic constructor undefined

I am learning java and generics and stuck in some problem.我正在学习 java 和 generics 并遇到了一些问题。 I have read all the problems on generic posted on Stackoverflow but couldn't understand why this error occurs我已阅读 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());
    }

}

when i run this code it says当我运行这段代码时,它说

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

You need to pass an object of Student to the constructor, GenericClassEx(T data) .您需要将Student的 object 传递给构造函数GenericClassEx(T data) Instead of that, you are passing two arguments, "prince" and d to it.取而代之的是,您将两个 arguments、 "prince"d传递给它。

Replace代替

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

with

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

As a side note, the constructor, Float(double value) is deprecated since Java-9.附带说明一下,构造函数Float(double value)自 Java-9 以来已被弃用。

Replace代替

Float d = new Float(10);

with

Float d = Float.valueOf(10);

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

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