Java扩展了一般指定的类型 [英] Java extend generically specified type

查看:107
本文介绍了Java扩展了一般指定的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何,我可以这样做:

  Class extends< T extends ClassB> 

只要该类扩展了一般指定的类的类,是否可以让一个类扩展一个类必须扩展?



它的语法/结构是什么?

解决方案

不,那是不可能的。我不认为这样做会有多大意义 - 当您使用泛型并以这种方式指定类时,您只能获得指定类中的信息。

对于正常使用(例如容器),这是有道理的,因为它可以让您依赖特定的类或接口的方法,同时能够确保额外的类型安全。但是,对于扩展类来说,这并不会有多大意义 - 因为只能依赖 ClassB 的方法,所以它在功能上相同的只是做类扩展ClassB



为了让你的想法变得有意义,你需要能够接受你定义的类,并将类型传递给扩展。但是,这会与多重继承有许多相同的缺陷 - 如果在您传入泛型的类中也定义了 Class 中首次定义的方法,那么您将执行什么操作,但不在 ClassB 中?在Java中没有多重继承是一个设计决定,并且具有这种工作方式的泛型会与此相反。

总之,类似这样的事情可能会像多重继承或将与正常继承相同。

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?

解决方案

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.

这篇关于Java扩展了一般指定的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆