Emily Tsang
Emily Tsang

Reputation: 115

Multiple Level of Inheritance

I have the following Java class with multiple level of inheritance with certain type parameters. I want to use the type parameter T in class B.

class B extends C {
}
class C<T extends D> {
}
class D {
}

However, he following doesn't compile:

class B extends C {
    T t;
}
class C<T extends D> {
}
class D {
}

Although I can define the variable t in class C, but it is not a good coding practice. How can I define the following (This doesn't compile as well)?

class B extends C<T extends D> {
}

Thanks!

Upvotes: 9

Views: 186

Answers (2)

Seelenvirtuose
Seelenvirtuose

Reputation: 20608

Type parameters are not inherited!

If you want to have your class B generic, you should specify its own type parameter:

class B<T extends D> extends C<T> {
    T t;
    ...
}

Note that you must again constrain the type parameter T to have it extending D because it is constrained this way in class C.

Upvotes: 5

Eran
Eran

Reputation: 393781

It should be :

class B<T extends D> extends C<T> {
}

Upvotes: 1

Related Questions