3

I am working with Java generics. Here is a code example followed by the question.

public class Test<T extends Comparable<T>>  {

    T data;

    public Test(T data) {

           this.data = data;
    }

    public T getData() {

            return this.data;
    }
}

class MyClass<T extends Comparable<T>> extends Test<T> {
        //if I remove this constructor, code will not compile
    public MyClass(T data) {

        super(data);
    }
}

In MyClass, if I do not have the constructor I get the following compile time error:

Implicit super constructor Test<T>() is undefined for default constructor. Must define an explicit constructor

Why does the compiler make me do this?

Rob L
  • 3,073
  • 6
  • 31
  • 61
  • 5
    This has nothing to do with generics, in point of fact. – Louis Wasserman Mar 17 '14 at 20:27
  • As soon as you declare a constructor, the implied no-argument constructor no longer exists. Also, constructors are not inherited. This is fairly basic Java language rules, it's unrelated to generics. – Jason C Mar 17 '14 at 20:32
  • possible duplicate of [Java default constructor](http://stackoverflow.com/questions/4488716/java-default-constructor) – Jason C Mar 17 '14 at 20:33
  • That link was helpful. Thank you! – Rob L Mar 17 '14 at 20:34
  • @user3270407 By the way, simply removing the `super(data)` call is sufficient to produce a compiler error; even with your subclass constructor still there. – Jason C Mar 17 '14 at 20:36
  • Ok and after looking at and reading the possible duplicate question you pointed out that makes total sense now. Thanks. – Rob L Mar 17 '14 at 20:41

1 Answers1

5

(This problem is not related to generics.)

Test does not have a default (i.e. no argument) constructor.

Therefore your child class needs to call explicitly the single constructor that you've provided in Test. (The compiler cannot figure out what to do due to this ambiguity - how would it know which argument(s) to pass - so it raises a compile-time error.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Oh ok. Do you know why that is? – Rob L Mar 17 '14 at 20:28
  • 3
    It's part of the Java Language Specification (JLS). C++ has the same property. The compiler-generated default constructor is automatically deleted if you supply one with arguments. – Bathsheba Mar 17 '14 at 20:29
  • Because the default constructor for `MyClass` -- or any class without an explicit constructor -- is always a no-arg constructor that just calls `super()`, which doesn't actually work here. – Louis Wasserman Mar 17 '14 at 20:29
  • 1
    @user3270407 due to ambiguity, there is no way for the VM to know what to pass as an argument elsewise. – Obicere Mar 17 '14 at 20:29
  • 2
    @user3270407 As soon as you declare a constructor in a class, it doesn't have a default constructor anymore. – fge Mar 17 '14 at 20:30
  • Ok. thank you guys for the helpful feedback and clarification. – Rob L Mar 17 '14 at 20:36