HAS-A Relationship

HAS-A Relationship in Java

The HAS-A relationship in Java is a type of association between classes where one class has a reference to another class as a member variable. It represents a "has-a" or "contains-a" relationship, indicating that one class has another class as part of its composition.

How to Use HAS-A Relationship

The HAS-A relationship is used when one class needs to utilize the functionalities or properties of another class. It promotes code reuse and allows for building complex class structures.

Example: Car and Engine

Let's consider an example where a Car class has a reference to an Engine class:

    
      class Engine {
          // Engine properties and methods
          public void start() {
              System.out.println("Engine started.");
          }
      }
      
      class Car {
          private Engine engine; // HAS-A relationship
      
          public Car() {
              engine = new Engine(); // Initialize the engine object
          }
      
          public void startCar() {
              engine.start(); // Delegate the start functionality to the engine object
          }
      }
      
      public class Main {
          public static void main(String[] args) {
              Car car = new Car();
              car.startCar(); // Start the car, which internally starts the engine
          }
      }
    
  

In the above example, the Car class has a reference to the Engine class. By creating an instance of the Car class, we also initialize an Engine object within it. The Car class can then utilize the functionalities of the Engine class by delegating certain operations to it. In this case, the startCar() method invokes the start() method of the Engine class, starting the engine of the car.

Go To OOPS Page Click Here

Post a Comment

Previous Post Next Post