Has-A Relationship - Notes by Shariq SP

Has-A Relationship in Java

The "Has-A" relationship in Java, also known as composition or aggregation, describes a relationship between two classes where one class contains an instance of another class as a member variable. This relationship allows one class to use functionality provided by another class without inheriting from it.

Implementation

In the "Has-A" relationship, one class, known as the container or composite class, contains an instance of another class, known as the component or contained class, as a member variable. The container class can then use the methods and properties of the contained class to achieve its functionality.

Example:


        class Engine {
            public void start() {
                System.out.println("Engine started");
            }
        }
        
        class Car {
            private Engine engine;
        
            public Car() {
                this.engine = new Engine();
            }
        
            public void startCar() {
                engine.start();
            }
        }
        
        public class Main {
            public static void main(String[] args) {
                Car car = new Car();
                car.startCar();
            }
        }
            

Benefits

  • Code Reusability: By encapsulating the functionality of one class within another, the "Has-A" relationship promotes code reuse and modularity.
  • Flexibility: The container class can be easily composed of different components, allowing for flexibility in design and implementation.
  • Encapsulation: Encapsulating functionality within a contained class helps to hide implementation details and reduces dependencies between classes.
  • Separation of Concerns: The "Has-A" relationship allows for better separation of concerns by dividing functionality into smaller, more manageable components.