Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to have a constructor in this Java generic subclass?

Tags:

java

subclass

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?

like image 528
Rob L Avatar asked Jan 01 '26 12:01

Rob L


1 Answers

(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.)

like image 190
Bathsheba Avatar answered Jan 03 '26 13:01

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!