Search code examples
javainheritancesubclassmultiple-inheritancesuperclass

Java: Can a class inherit from two super classes at the same time?


I have a class Journey which I want to make a superclass and another class plannedjourney. The plannedjourney class extends JFrame since it contains forms..However I also want this class to extends Journey..

Is there a possible way to do this?


Solution

  • Don't mix models and views. If you keep both domains clearly separated, then you won't be in need of multiple inheritance (this time).

    You have one model class for journeys and a viewer for such journeys. The viewer should subclass Component and be displayed (somewhere) in your window (a JFrame instance).

    This viewer takes one journey object and presents the journey's properties. Journey alone has all information about a journey, only the viewer knows how to present a journey to the user:

     public class PlannedJourney extends JPanel {
       private Journey journey;
       public JourneyViewer(Journey journey) {
         this.journey = journey;
    
         // build this panel based on the journey object
         // (add labels, subpanels, widgets, ...)
       }
     }
    

    Now you can create an instance of PlannedJourney and add it to the applications JFrame at the appropriate position.