Alex Hope O'Connor
Alex Hope O'Connor

Reputation: 9714

Java extend generically specified type

Is there anyway I could do something like this:

Class extends <T extends ClassB>

Can you have a class extend a class as long as that class extends the class that the generically specified class must extend?

What would be the syntax/structure for it?

Upvotes: 1

Views: 451

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234857

I think that because of type erasure, you won't be able to do this. For instance, you can't even do this:

class A<T> {
    class B extends T {
    }
}

Upvotes: 2

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68172

No, that is not possible. I don't think it would make much sense either—when you use generics and specify a class this way, you only have the information from the class you specified.

For normal use (containers, for example), this makes sense because it lets you rely on a particular class or interface's methods while being able to ensure additional type safety. However, for extending a class, this would not really make much sense—since you can only rely on the methods of ClassB, it would be functionally identical to just doing Class extend ClassB.

For your idea to make much sense, you would need to be able to take the class you've defined and pass in a type to "extend". However, this would have many of the same pitfalls as multiple inheritance—what would you do if a method first defined in Class was also defined in the class you pass in to the generics, but not in ClassB? Not having multiple inheritance in Java was a design decision and having generics that work like that would go against that.

In short, something like this would either be like multiple inheritance or would be identical to normal inheritance.

Upvotes: 3

Related Questions