9

Here is my question.

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

Why is it illegal? Could you please explain it.

7
  • @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
    Commented Jun 4, 2016 at 18:14
  • @DeadMG You'd have thought so, but I can't find them...
    – Jules
    Commented Jun 4, 2016 at 19:59
  • What should new Gen<FileInputStream>() do?
    – user20574
    Commented Jun 4, 2016 at 21:34
  • 2
    @scriptin C++ lets you do that
    – user20574
    Commented Jun 4, 2016 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 Commented Jun 4, 2016 at 21:53

1 Answer 1

16

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.

7
  • 1
    After compile it will be replaced by Object . ob = new Object();
    – alakhya
    Commented Jun 4, 2016 at 19:12
  • 1
    No it won't, you can't cast Object to T. It would break.
    – Zalomon
    Commented Jun 9, 2016 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
    Commented Oct 21, 2016 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 Commented Oct 22, 2016 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
    Commented Oct 22, 2016 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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