What is Has-A-Relation in Java?
Association is the relation between two separate classes which establishes through their Objects. Composition and Aggregation are the two forms of association. In Java, a Has-A relationship is otherwise called composition. It is additionally utilized for code reusability in Java. In Java, a Has-A relationship essentially implies that an example of one class has a reference to an occasion of another class or another occurrence of a similar class. For instance, a vehicle has a motor, a canine has a tail, etc. In Java, there is no such watchword that executes a Has-A relationship. Yet, we generally utilize new catchphrases to actualize a Has-A relationship in Java.
Has-a is a special form of Association where:
- It represents the Has-A relationship.
- It is a unidirectional association i.e. a one-way relationship. For example, here above as shown pulsar motorcycle has an engine but vice-versa is not possible and thus unidirectional in nature.
- In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity.
This shows that class Pulsar Has-a an engine. By having a different class for the engine, we don’t need to put the whole code that has a place with speed inside the Van class, which makes it conceivable to reuse the Speed class in numerous applications.
In an Object-Oriented element, the clients don’t have to make a big deal about which article is accomplishing the genuine work. To accomplish this, the Van class conceals the execution subtleties from the clients of the Van class. Thus, essentially what happens is the clients would ask the Van class to do a specific activity and the Van class will either accomplish the work without help from anyone else or request that another class play out the activity.
Implementation: Here is the implementation of the same which is as follows:
- Car class has a couple of instance variable and few methods
- Maserati is a type of car that extends the Car class that shows Maserati is a Car. Maserati also uses an Engine’s method, stop, using composition. So it shows that a Maserati has an Engine.
- The Engine class has the two methods start() and stop() that are used by the Maserati class.
Car Color= RED Max Speed= 150 Started: Stopped: