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

后端 未结 3 1106
礼貌的吻别
礼貌的吻别 2021-01-18 21:10

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

相关标签:
3条回答
  • 2021-01-18 21:13

    Prefer Composition over Inheritance

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

    0 讨论(0)
  • 2021-01-18 21:28

    You can do as below

    public class Files extends JPanel{
    }
    
    public class FileSub1 extends Files{
    }
    
    public class FileSub2 extends Files{
    }
    
    0 讨论(0)
  • 2021-01-18 21:31

    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() {}
    }
    
    0 讨论(0)
提交回复
热议问题