English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

The difference between inheritance and composition in Java

Composition is a design technique where your class can have an instance of another class as a field of your class. Inheritance is a mechanism where an object can obtain the properties and behaviors of the parent object by extending the class.

Composition and inheritance both provide code reusability through related classes. When you use composition, we can also obtain the functionality of inheritance. Here are the differences. 

Serial NumberKeyInheritanceComposition
1
Basic 
Inheritance is a "is" relationship
Composition is a "has" relationship 
2
Code Reuse 
In inheritance, a class can only extend one interface, so you can only reuse code in one class 
We can reuse code in multiple classes 
3
Scope 
 Inheritance provides its functionality at compile time
Easily implement composition at runtime 
4
Finally 
 We cannot reuse the code from the last class 
It even allows code reuse from the final class
5
Methods 
It exposes the public methods and protected methods of the superclass 
It does not expose. They interact using the public interface.

Example of Inheritance

class Animal{
   String name = "Orio";
{}
class Dog extends Animal{
   String type = "Dog";
   public static void main(String args[]) {
      Dog p = new Dog();
      System.out.println("Name:")+p.name);
      System.out.println("Type:")+p.type);
   {}
{}

Composition Example

public class Student {
{}
public class College {
   private Student student;
   public College() {
      this.student = new Student();
   {}
{}
You Might Also Like