I am learning java and generics and stuck in some problem. I have read all the problems on generic posted on Stackoverflow but couldn't understand why this error occurs
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)
. Instead of that, you are passing two arguments, "prince"
and d
to it.
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.
Replace
Float d = new Float(10);
with
Float d = Float.valueOf(10);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.