HAS A relationship in Java
The HAS-A relationship in Java represents composition, where one class contains a reference to another class, indicating that one class “has” an instance of another class. This is used to model a relationship where one object is composed of one or more objects from other classes.
Table of Contents
Key Points of HAS A Relationship
- Composition: HAS-A relationship is established through composition, where a class includes instances of other classes as its members.
- Encapsulation: Promotes encapsulation by allowing complex types to be built from simpler types.
- Reusability: Enhances code reusability by composing new functionality from existing classes.
Example
```java
// Class representing an Engine
class Engine {
void start() {
System.out.println("Engine starts.");
}
}
// Class representing a Car
class Car {
// Car HAS-A Engine
private Engine engine;
Car() {
engine = new Engine(); // Composing a Car with an Engine
}
void startCar() {
engine.start(); // Delegating behavior to the Engine
System.out.println("Car starts.");
}
}
public class Test {
public static void main(String[] args) {
Car myCar = new Car();
myCar.startCar(); // Output: Engine starts.
// Car starts.
}
}
```
Explanation
In this example, the `Car` class has an instance of the `Engine` class, establishing a HAS-A relationship. The `Car` class is composed of an `Engine` object and uses it to start the car. This illustrates how composition allows objects to contain and use other objects to achieve desired functionality.
Summary
The HAS-A relationship in Java, represented through composition, allows classes to contain instances of other classes. This promotes encapsulation and code reusability, enabling the creation of complex objects from simpler, reusable components.