tutorialcup
Aggregation in Java
Aggregation in Java allows us to provide a reference for one class within another class. In other words, it supports a one-way relationship and implements a HAS-A relation. This is in contrast to the java inheritance concept that supports IS-A relation.
When two classes have a HAS-A relation, we say it implements aggregation. One best example we can think of is "Employee has a Car". We say this is unidirectional since a car cannot have an employee and only an employee can have a car.
Before we understand this with an example, let see why we need to use aggregation.
Usage of Aggregation in java
- Provides reusability of code
- We can directly access the methods and variables of the reference class
- Implements HAS-A relation
Example of Aggregation
Let us see how we can implement "Employee has a Car" in java using the aggregation concept. We create 2 classes Car and Employee. In the Employee class, we create a reference to the Car class by creating an object. Hence using this car object we can access all the properties of the Car class. So the Employee class has a unidirectional relationship with the Car class that implements aggregation.
This is a realtime example of aggregation where the company can track which employees are coming in their own vehicle to provide vehicle pass.
class Car {
String carname;
String color;
String regno;
Car(String carname, String color, String regno) {
this.carname = carname;
this.color = color;
this.
Aggregation in Java
Aggregation in Java allows us to provide a reference for one class within another class. In other words, it supports a one-way relationship and implements a HAS-A relation. This is in contrast to the java inheritance concept that supports IS-A relation.
When two classes have a HAS-A relation, we say it implements aggregation. One best example we can think of is "Employee has a Car". We say this is unidirectional since a car cannot have an employee and only an employee can have a car.
Before we understand this with an example, let see why we need to use aggregation.
Usage of Aggregation in java
- Provides reusability of code
- We can directly access the methods and variables of the reference class
- Implements HAS-A relation
Example of Aggregation
Let us see how we can implement "Employee has a Car" in java using the aggregation concept. We create 2 classes Car and Employee. In the Employee class, we create a reference to the Car class by creating an object. Hence using this car object we can access all the properties of the Car class. So the Employee class has a unidirectional relationship with the Car class that implements aggregation.
This is a realtime example of aggregation where the company can track which employees are coming in their own vehicle to provide vehicle pass.
class Car {
String carname;
String color;
String regno;
Car(String carname, String color, String regno) {
this.carname = carname;
this.color = color;
this.