如何构建两级继承层次结构?

时间:2017-06-08 15:55:13

标签: java oop design-patterns

我假设一个具有多个继承层次结构的类可以分解为: 假设一架飞机有4种组合:

1.  Subsonic & commercial
2.  Subsonic & jet fighter
3.  Supersonic & commercial
4.  Supersonic & jet fighter

现在我的非面向对象类看起来像这样

Class Airplane {

   Void SubsonicAndCommercial {
       print
    }

    void subsonicAndJet  {

   }

  void supersonicAndCommercial {

  }

  void supersonicAndJet {

 }

}

现在我需要将平面类拆分为子类。什么是最常见的方法? 这是一个2级的层次结构吗? 即 Iface Plane Iface Subsonic,超音速扩展飞机
4-Subclass Jet扩展超音速,喷射扩展亚音速......等等。

2 个答案:

答案 0 :(得分:2)

在Java中,类永远不能扩展多个类,因此这看起来像接口的作业。您应该为Subsonic,Supersonic,Commercial和Fighter建立接口。然后你可以像这样实现它们

public class SubCommercialPlane implements Subsonic, Commercial


public class SuperCommercialPlane implements Supersonic, Commercial


public class SubFighterPlane implements Subsonic, Fighter


public class SuperCommercialPlane implements Supersonic, Fighter

这可能是使用简单的java层次结构实现此目的的最佳方法。如果您想以更复杂的方式解决这个问题,请查看实体组件模型,该模型在此维基百科文章中有详细解释:

https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system

答案 1 :(得分:2)

一种方法是为Subsonic,Supersonic,Commercial和Military定义接口。然后定义实现适当接口对的类。

这使您可以定义接受超音速界面的方法,无论是商业还是军事,都可以使用。

您可以定义如下界面:

public interface IAirplane {
   // Method declarations appropriate for all planes.  
}

public interface ISupersonic extends IAirplane {
   // Method declarations specific to Supersonic aircraft.
}

在为Subsonic,Commercial和Military定义类似的接口之后,您可以定义实现适当接口的类。例如:

public class SupersonicJetFighter implements ISupersonic, IMilitary {
   // Implementations of methods in IAirplane, ISupersonic and IMilitary
}

如果某些代码在多个IAirplane实现之间很常见,则可以引入一个抽象类。

public abstract class AbstractAirplane implements IAirplane {
   // Common methods.
}

public class SupersonicJetFighter 
extends AbstractAirplane 
implements ISupersonic, IMilitary {
   // Implementations of undefined methods in IAirplane, ISupersonic and IMilitary
}
相关问题