1

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?

2
  • Just curious: what are you really trying to accomplish? Could you describe how or for what you would use that kind of capability if it did exist? Commented May 25, 2011 at 4:34
  • I am trying to do up a little bit of an MVC class structure and I wanted the base View class to inherit Container methods and properties. But in the extended classes I want the class to be extended by JFrame for example. Commented May 25, 2011 at 5:09

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually ClassB is a Container, and I want to be able to access the Container methods on the base class and access the sub type methods in sub classes.
2

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 {
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.