Поиск по сайту:

Композиция против наследования


Composition vs Inheritance — один из часто задаваемых вопросов на собеседовании. Вы, должно быть, также слышали об использовании композиции вместо наследования.

Композиция против наследования

И композиция, и наследование — это концепции объектно-ориентированного программирования. Они не привязаны к какому-либо конкретному языку программирования, такому как Java. Прежде чем мы сравним композицию с наследованием программно, давайте дадим их краткое определение.

Состав

Композиция — это метод проектирования в объектно-ориентированном программировании для реализации связи между объектами. Композиция в java достигается за счет использования переменных экземпляров других объектов. Например, человек, у которого есть работа, реализован, как показано ниже, в объектно-ориентированном программировании Java.

package com.journaldev.composition;

public class Job {
// variables, methods etc.
}
package com.journaldev.composition;

public class Person {

    //composition has-a relationship
    private Job job;

    //variables, methods, constructors etc. object-oriented

Наследование

Наследование — это метод проектирования в объектно-ориентированном программировании для реализации отношений типа «есть» между объектами. Наследование в Java реализовано с помощью ключевого слова extends. Например, отношение «Кошка — животное» в Java-программировании будет реализовано, как показано ниже.

package com.journaldev.inheritance;
 
public class Animal {
// variables, methods etc.
}
package com.journaldev.inheritance;
 
public class Cat extends Animal{
}

Композиция над наследованием

И композиция, и наследование способствуют повторному использованию кода с помощью различных подходов. Итак, какой выбрать? Как сравнить композицию и наследование. Вы, должно быть, слышали, что в программировании вы должны отдавать предпочтение композиции, а не наследованию. Давайте рассмотрим некоторые причины, которые помогут вам выбрать композицию или наследование.

  1. Inheritance is tightly coupled whereas composition is loosely coupled. Let’s assume we have below classes with inheritance.

    package com.journaldev.java.examples;
    
    public class ClassA {
    
    	public void foo(){	
    	}
    }
    
    class ClassB extends ClassA{
    	public void bar(){
    		
    	}
    }
    

    For simplicity, we have both the superclass and subclass in a single package. But mostly they will be in the separate codebase. There could be many classes extending the superclass ClassA. A very common example of this situation is extending the Exception class. Now let’s say ClassA implementation is changed like below, a new method bar() is added.

    package com.journaldev.java.examples;
    
    public class ClassA {
    
    	public void foo(){	
    	}
    	
    	public int bar(){
    		return 0;
    	}
    }
    

    As soon as you start using new ClassA implementation, you will get compile time error in ClassB as The return type is incompatible with ClassA.bar(). The solution would be to change either the superclass or the subclass bar() method to make them compatible. If you would have used Composition over inheritance, you will never face this problem. A simple example of ClassB implementation using Composition can be as below.

    class ClassB{
    	ClassA classA = new ClassA();
    	
    	public void bar(){
    		classA.foo();
    		classA.bar();
    	}
    }
    
  2. There is no access control in inheritance whereas access can be restricted in composition. We expose all the superclass methods to the other classes having access to subclass. So if a new method is introduced or there are security holes in the superclass, subclass becomes vulnerable. Since in composition we choose which methods to use, it’s more secure than inheritance. For example, we can provide ClassA foo() method exposure to other classes using below code in ClassB.

    class ClassB {
    	
    	ClassA classA = new ClassA();
    	
    	public void foo(){
    		classA.foo();
    	}
    	
    	public void bar(){	
    	}
    	
    }
    

    This is one of the major advantage of composition over inheritance.

  3. Composition provides flexibility in invocation of methods that is useful with multiple subclass scenario. For example, let’s say we have below inheritance scenario.

    abstract class Abs {
    	abstract void foo();
    }
    
    public class ClassA extends Abs{
    
    	public void foo(){	
    	}
    	
    }
    
    class ClassB extends Abs{
    		
    	public void foo(){
    	}
    	
    }
    
    class Test {
    	
    	ClassA a = new ClassA();
    	ClassB b = new ClassB();
    
    	public void test(){
    		a.foo();
    		b.foo();
    	}
    }
    

    So what if there are more subclasses, will composition make our code ugly by having one instance for each subclass? No, we can rewrite the Test class like below.

    class Test {
    	Abs obj = null;
    	
    	Test1(Abs o){
    		this.obj = o;
    	}
    	
    	public void foo(){
    		this.obj.foo();
    	}
    
    }
    

    This will give you the flexibility to use any subclass based on the object used in the constructor.

  4. One more benefit of composition over inheritance is testing scope. Unit testing is easy in composition because we know what all methods we are using from another class. We can mock it up for testing whereas in inheritance we depend heavily on superclass and don’t know what all methods of superclass will be used. So we will have to test all the methods of the superclass. This is extra work and we need to do it unnecessarily because of inheritance.

Это все, что касается композиции и наследования. У вас достаточно причин предпочесть композицию наследованию. Используйте наследование только тогда, когда вы уверены, что суперкласс не будет изменен, в противном случае используйте композицию.