为什么不应该扩展 JFrame 和其他组件? [英] Why shouldn't you extend JFrame and other components?

查看:26
本文介绍了为什么不应该扩展 JFrame 和其他组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到过几次,但在我看到的帖子中,没有人解释它.为什么我不应该扩展 JFrame(或任何组件)?是否存在我应该扩展组件的条件,或者这是您不应该扩展的坚定规则?

I've seen this come up here a few times, but in the postings I've seen, no one explained it. Why shouldn't I extend JFrame (or any component)? Are there conditions where I should extend a component, or is this a firm rule that you don't?

推荐答案

一般来说,扩展组件趋向于严格使用组件.这在设计方面以不必要的方式严重限制了您的选择,使您的类无法扩展不同的类,您无法隐藏 JFrame 的方法,从而导致在使用类时更难维护并更容易触发意外错误.

Generally speaking, extending the component tends to be done strictly to use the component. This severely limits your options in unnecessary ways in terms of design, so that your classes can't extend different classes, you can't hide the JFrame's methods causing it to be more difficult to maintain and easier to trigger unexpected bugs when using the class.

通常的意图是严格使用类来绘制框架,并且组合优先于继承.

Typically the intention is strictly to use the class to draw a frame, and composition is preferred over inheritance.

话虽如此,当您打算让子类向 Frame 添加项目特定的功能(例如便利方法等)时,子类化应该没问题,在该功能中子类将用于代替 Frame 本身,但用作框架一般,而不是作为应用程序中特定框架的视图.

That being said, subclassing should be fine when you intend your subclass to add project-specific functionality to the Frame (such as convenience methods and the like) where the subclass would be used instead of the Frame itself, but used as a frame in general, not as a view of a specific frame in the application.

这篇关于为什么不应该扩展 JFrame 和其他组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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