跳过继承树中的类实现
我有以下类结构:
Class Human, with message("Hello, ")
Class Townsmen extends Human, with message("I live in town.")
Class Merchant extends Townsmen, with message("I'm merchant.")
Merchant 的实例是否可以使用 super
调用说“你好,我是商人。”?我有一个Java程序,代码复杂得多,但思想是一样的。此外,我无法修改人类或城镇居民类别。
I have the following class structure:
Class Human, with message("Hello, ")
Class Townsmen extends Human, with message("I live in town.")
Class Merchant extends Townsmen, with message("I'm merchant.")
Is it possible for an instance of Merchant to say "Hello, I'm merchant.", using super
calls? I have a program in Java, and the code is much more complex, but the idea is the same. In addition I cannot modify Human nor Townsmen classes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,您可以使用反射来获得您想要的东西(请参阅 为什么 Java 中不允许 super.super.method(); ?)。但是,不要!
您面临的问题可以使用正确的设计来解决。
作为一条经验法则 - 如果您试图实现语言本身试图限制的非常独特的东西,那么您的设计可能有问题。 (我的 2 美分;))
Well, you can hack around using reflection to get what you want (see Why is super.super.method(); not allowed in Java?). However, DONT!
The problem you are facing is solvable using the right design.
As a thumb rule - If you are trying to achieve something very unique that the language itself tries to restrict, probably something is wrong with your design. (my 2 cents ;))
我能想到的只有:
类 Merchant 扩展了 Human,带有消息(“我是商人。”)
我认为您不能跳过您不喜欢的超类构造函数 - 这不是继承的工作原理。
All I can think of is:
Class Merchant extends Human, with message("I'm merchant.")
I don't think you can skip the superclass constructors you don't like - this isn't how inheritance works.
这在 Java 中是不可能的,因为 Java 不允许多重继承。正确的方法是:
城镇成员拥有城镇居民该商人继承的任何逻辑。
由于您无法做到这一点,因此您需要让 Merchant 扩展 Human 并重新实现该逻辑。
This isn't possible in Java, which doesn't allow multiple inheritance. The correct way to do this would be:
With TownMember having whatever logic that townsmen has that merchant inherits.
Since you can't do that, you're going to need to have Merchant extend Human and just re-implement that logic.
您可以让 Merchant 不调用超级方法并执行 Human.message 执行的操作。如果权限有问题,它可以使用反射。
然而,商人似乎不是城镇居民,应该延伸为人类。
You can have Merchant not call a super method and do what ever the Human.message does. It can use reflections if permissions is a problem.
However it appears that a Merchant is not a Townsman and should extend Human.