Inheritance vs Delegation in Java

The following tutorial explores Inheritance vs Delegation in Java language.

What is Inheritance?

Inheritance is among the four main features (Encapsulation, Abstraction, Polymorphism) of OOPS. Using inheritance one class can inherit all the properties of another class. The class inheriting the properties is called the child class and the class being inherited from is called the parent class. Inheritance is implemented using the “extends” keyword in Java.

There are four types of inheritance:

  1. Single – single inheritance can be defined as a single class inserting from a superclass or a base class. Single inheritance is one of the most simple forms of inheritance in Java
  2. Multiple – multiple inheritance is when one class inherits from more than one superclass.
  3. Multi-level – multi-level inheritance is when one class inherits from a class which in turn inherits from another class.
  4. Hybrid inheritance – makes use of several different types of inheritance.

What is Delegation?

Delegation is passing or assigning a duty or task to a secondary party. Delegation is using the instance of a class as an instance variable and passes messages to the instance. Delegation emphasizes more on how instances relate to one another. Using delegation has several advantages over inheritance such as its ability to be dynamic even during run-time, which means it can be altered at run-time.

Java Program on Inheritance

class Dog {
    
    void info() 
    { 
        System.out.println("This is the dog class");    
    } 
}  
class GoldenRetriever extends Dog { 
  
    void breed() 
    { 
        System.out.println("Golden Retriever");
    } 
} 
public class InheritanceProg {

    public static void main(String[] args) {
        
        Dog d = new Dog();
        d.info();
        GoldenRetriever g = new GoldenRetriever();
        g.breed();
    } 
}

Output:

This is the dog class
Golden Retriever

Java Program on Delegates

class Dog {
    
    void info() 
    { 
        System.out.println("This is the dog class");    
    } 
}  
class GoldenRetriever extends Dog { 
    
    Dog d = new Dog();
    void breed() 
    { 
        System.out.println("Golden Retriever");
    } 
} 
public class DelegatesProg {

    public static void main(String[] args) {
    
      GoldenRetriever g = new GoldenRetriever();
      g.info();
    } 
}

Output:

This is the dog class

From the above two Java code samples, you can see the Inheritance vs Delegation comparison.

Leave a Reply

Your email address will not be published. Required fields are marked *