跳过继承树中的类实现

发布于 2024-11-29 12:49:36 字数 309 浏览 0 评论 0原文

我有以下类结构:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

情绪 2024-12-06 12:49:36

好吧,您可以使用反射来获得您想要的东西(请参阅 为什么 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 ;))

花开柳相依 2024-12-06 12:49:36

我能想到的只有:
类 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.

冷情妓 2024-12-06 12:49:36

这在 Java 中是不可能的,因为 Java 不允许多重继承。正确的方法是:

      Human
     /     
  TownMember
  /       \
 Townsmen  Merchant

城镇成员拥有城镇居民该商人继承的任何逻辑。

由于您无法做到这一点,因此您需要让 Merchant 扩展 Human 并重新实现该逻辑。

This isn't possible in Java, which doesn't allow multiple inheritance. The correct way to do this would be:

      Human
     /     
  TownMember
  /       \
 Townsmen  Merchant

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.

街角卖回忆 2024-12-06 12:49:36

您可以让 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文