Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics Default Constructor Java

Tags:

java

generics

public class Sample<T>{

 T data;

   Sample(){

     data = ????;

  }

}

How can i assign a default value to data ?

like image 783
Ravit Teja Avatar asked Oct 18 '10 07:10

Ravit Teja


2 Answers

Bozho is right (you can't). If you definitely want it to start off with a value, make that value an argument to the constructor. For instance:

public class Sample<T> {
  T data;
  Sample(T data) {
     this.data = data;
  }
}
like image 87
johncip Avatar answered Oct 16 '22 08:10

johncip


You can't. The type T is erased at runtime, so you can't instantiate it.

If you pass a Class argument to the Sample(..) constructor, you can call clazz.newInstance()

like image 40
Bozho Avatar answered Oct 16 '22 09:10

Bozho