Difference between Inheritance and Composition

前端 未结 17 2301
忘了有多久
忘了有多久 2020-11-22 02:35

Are Composition and Inheritance the same? If I want to implement the composition pattern, how can I do that in Java?

17条回答
  •  孤城傲影
    2020-11-22 03:14

    Inheritance brings out IS-A relation. Composition brings out HAS-A relation. Strategy pattern explain that Composition should be used in cases where there are families of algorithms defining a particular behaviour.
    Classic example being of a duck class which implements a flying behaviour.

    public interface Flyable{
     public void fly();
    }
    
    public class Duck {
     Flyable fly;
    
     public Duck(){
      fly = new BackwardFlying();
     }
    }
    

    Thus we can have multiple classes which implement flying eg:

    public class BackwardFlying implements Flyable{
      public void fly(){
        Systemout.println("Flies backward ");
      }
    }
    public class FastFlying implements Flyable{
      public void fly(){
        Systemout.println("Flies 100 miles/sec");
      }
    }
    

    Had it been for inheritance, we would have two different classes of birds which implement the fly function over and over again. So inheritance and composition are completely different.

提交回复
热议问题