Here is my question.
class Gen<T> {
T ob;
Gen() {
ob = new T(); // Illegal!!!
}
}
Why is it illegal? Could you please explain it.
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.
Sign up to join this communityThis 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.
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
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.
Oct 22, 2016 at 16:42
new Gen<FileInputStream>()
do?