Java inheritance: How to achieve something similar to “multiple inheritance” when it is not allowed in Java?

半腔热情 提交于 2020-01-11 08:59:14

问题


This is a question mostly about Java inheritance. I am developing a program which has 2 windows, both of which will be developed in separate classes which will extend JPanel. The first class is "FileSub1" and the second one is "FileSub2".

There are a lot of methods that are common to these two classes, so I would like to create a class called "Files" and make "FileSub1" and "FileSub2" its subclasses. But Java doesn't support multiple inheritance! What can I do here?


回答1:


I don't see why you need multiple inheritance. As far as I can tell you should be fine with a an abstract base class that implements the common methods:

public abstract class AbstractFilePanel extends JPanel
{
    public void commonMethod1() {}
}

public class FileSub1 extends AbstractFilePanel 
{
    public void sub1Method() {}
}

public class FileSub2 extends AbstractFilePanel 
{
    public void sub2Method() {}
}



回答2:


Prefer Composition over Inheritance

Include a FileThing in your JPanel subclass, instead of making it a FileThing and a JPanel.




回答3:


You can do as below

public class Files extends JPanel{
}

public class FileSub1 extends Files{
}

public class FileSub2 extends Files{
}


来源:https://stackoverflow.com/questions/10854685/java-inheritance-how-to-achieve-something-similar-to-multiple-inheritance-whe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!