当子类重写超类方法时如何正确建模更改的返回类型

发布于 2024-09-25 15:56:44 字数 797 浏览 0 评论 0原文

我要问的问题是我是否正确地建模了 UserControl 的子类。具体来说,基类有一个方法public abstract JComponent toComponent()。在实现过程中,子类应该重写该方法,保持方法签名相同,除了 return 语句应该返回一个专门的组件,即 return new JButton(); 虽然我是图的创建者,但它了解实现应该如何进行看看我可以看到另一个程序员如何查看该图并得出以下结论。

public JButton toComponent(){
      if(GUIComponent == null || !(GUIComponent instanceof JButton)){
        return new JButton();
      } else{
        return (JButton) GUIComponent;
     }
}

预期的实现是:

  public JComponent toComponent(){
          if(GUIComponent == null || !(GUIComponent instanceof JButton)){
            return new JButton();
          } else{
            return GUIComponent;
         }
    }

在这种情况下,实现可能不是很重要,但在更复杂的系统中,它可能被证明是至关重要的。所以我想知道如何正确建模方法的重写以返回不同的类型,同时保持签名准确。

The question I am asking is whether I have modelled the subclasses of UserControl Correctly. Specifically the base class has a method public abstract JComponent toComponent(). During implementation the subclasses should override the method keeping the method signature the same except that the return statement should return a specialized Component ie return new JButton(); While I the creator of the diagram understand how the implementation should look I can see how another programmer may look at the diagram and come to the following conclusion.

public JButton toComponent(){
      if(GUIComponent == null || !(GUIComponent instanceof JButton)){
        return new JButton();
      } else{
        return (JButton) GUIComponent;
     }
}

Where the intended implementation is:

  public JComponent toComponent(){
          if(GUIComponent == null || !(GUIComponent instanceof JButton)){
            return new JButton();
          } else{
            return GUIComponent;
         }
    }

In this instance the implementation may not be of great concern, however in a more complex system it may prove to be crucial. So I would like to know how to correctly model the overriding of a method to return a different type while keeping the signature exact.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

守望孤独 2024-10-02 15:56:44

如果您的意图是子类签名应该返回 JComponent 那么图表肯定应该这样说,而不是说它们返回 JButton 或其他什么?

您的图表应该指定实际的接口。目前它揭示了创建 JButton 对象的实现细节。

If your intent is that the child class signatures should return JComponent then surely the diagram should say this, rather than saying that the they return JButton or whatever?

Your diagram should specify the actual interface. At present it's revealing a detail of implementation, that the a JButton object is created.

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