Java中如何组合类
我有一个 Android 应用程序,其中包含一个 Activity、一个线程和一个用于保存数据的类。
我创建了一个抽象类ActivityTemplate,它扩展了Activity 类并实现了一些回调,例如onTouchListener。这还包括一些抽象方法。 我创建了一个抽象类(ThreadTemplate),它扩展了 Thread 类并包含一些抽象方法。 我创建了一个抽象的 DataTemplate 类,它包含一些数据元素和一些简单的操作方法。
我可以通过派生三个类来生成我的应用程序,其中一个类来自上面的每个“模板”,但我真的希望能够将它们全部汇总到一个 MyTemplate 类中,我可以从中派生我的应用程序。
有点:
public class MyTemplate extends ActivityTemplate, ThreadTemplate, DataTemplate
然后
public class MyApp extends MyTemplate
但是 MyTemplate 类将无法编译,因为您只能扩展一个类。
有什么想法,还是我在问不可能的事情?
I have an Android app with an Activity, a Thread and a class to hold data.
I have created an abstract class ActivityTemplate which extends the Activity class and implements some callbacks, e.g. onTouchListener. This also includes some abstract methods.
I have created an abstract class (ThreadTemplate) which extends the Thread class and includes some abstract methods.
I have created an abstract DataTemplate class which holds some data elements and some simple methods to manipulate it.
I can produce my app by deriving three classes, one from each of the 'Template's above, but I really want to be able to roll them all up into a single MyTemplate class from which I can derive my app from.
Sort of:
public class MyTemplate extends ActivityTemplate, ThreadTemplate, DataTemplate
then
public class MyApp extends MyTemplate
But the MyTemplate class will not compile as you can only extend one class.
Any thoughts, or am I asking the impossible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用对象组合而不是继承:
使用继承时,请始终问自己一个问题:您的子类与父类是否具有“is-a”关系。在本例中,
MyApp
不是模板。它有一个模板。Use object composition instead of inheritance:
When using inheritance always ask yourself the question whether your subclass has an "is-a" relationship with the parent. In this case,
MyApp
is not a template. It has-a template.