Here is my question.
class Gen<T> {
T ob;
Gen() {
ob = new T(); // Illegal!!!
}
}
Why is it illegal? Could you please explain it.
This is impossible because of the following 2 reasons.
An answer may be to take a T factory in the constructor. Then Gen can request new Ts to its heart content.
T
, and checks to make sure that the code works for all possible T
. It doesn't know what T
is.
Commented
Oct 21, 2016 at 21:53
List<String> test=new ArrayList<>(); test.add(new Donkey())
would not be a compile error. Possibly we are meaning two different compile times, the compile time for the ArrayList
itself and the compile time for the calling context
Commented
Oct 22, 2016 at 10:48
List
or ArrayList#add
. That's in the code that uses it. When compiling ArrayList
, the compiler doesn't know anything about what T
is.
Commented
Oct 22, 2016 at 16:42
new Gen<FileInputStream>()
do?