Here is my question.

class Gen<T> {
    T ob;
    Gen() {
        ob = new T(); // Illegal!!!

Why is it illegal? Could you please explain it.

  • @DeadMG Are there languages which would allow some analogous code to compile and still guarantee no runtime errors in case when T happens to be something which cannot be instantiated with no-arg constructor (or at all)? – scriptin Jun 4 '16 at 18:14
  • @DeadMG You'd have thought so, but I can't find them... – Jules Jun 4 '16 at 19:59
  • What should new Gen<FileInputStream>() do? – user253751 Jun 4 '16 at 21:34
  • 1
    @scriptin C++ lets you do that – user253751 Jun 4 '16 at 21:34
  • 3
    @scriptin C# has new() constraint which allows to instantiate type parameters with no args constructors msdn.microsoft.com/en-us/library/sd2w2ew5.aspx – Esben Skov Pedersen Jun 4 '16 at 21:53

This is impossible because of the following 2 reasons.

  1. There is no guarantee that T has a no-args constructor (and for that matter isn't an interface or abstract class)
  2. Due to type erasure (required for backwards compatibility) the Type of T is known at compile time but not at run time, so what to construct wouldn't be known.

An answer may be to take a T factory in the constructor. Then Gen can request new Ts to its heart content.

  • 1
    After compile it will be replaced by Object . ob = new Object(); – alakhya Jun 4 '16 at 19:12
  • 1
    No it won't, you can't cast Object to T. It would break. – Zalomon Jun 9 '16 at 14:18
  • "the Type of T is known at compile time" It is not know at compile time. When compiling this method, the compiler just sees a T, and checks to make sure that the code works for all possible T. It doesn't know what T is. – user102008 Oct 21 '16 at 21:53
  • @user102008 That cannot be the case. If so 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 – Richard Tingle Oct 22 '16 at 10:48
  • @RichardTingle: But that's not in the code for 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. – user102008 Oct 22 '16 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.