Introduction
Java is an object-oriented programming language that supports inheritance. Inheritance is the ability to inherit the features and functionalities from another class. It supports the reuse of the same code. It allows the programmer to define a class in terms of another class. A relationship in Java means different relations between two or more classes. In Java, we can have a has-a relationship between classes, otherwise known as composition. A composition is a form of association, where an association is a relation between two classes that is established using their objects.
What is Has-a relationship
In Java, has-a relationship implies that an example of one class has a reference to an occasion of another class. There is no watchword to implement has-a relationship in Java. Has-a is a special form of association. Some of the important points of a has-a relationship are :
- It is a one-way relationship or a unidirectional association.
-
Both entries can survive independently in aggregation, which means ending one entity will not affect the other entity.
The above flowchart shows that the class Ktm has-a an engine.
Implementation
- The class Bike has a few instance variables and methods.
- Ktm is a type of Bike that extends the Bike class that shows Ktm is a Bike. Ktm also uses an Engine’s method, engine_kill, using composition, which shows that Ktm has an Engine.
- The Engine class has two methods naming engine_on() and engine_kill(), used by the Ktm class.
Example
// Parent class
public class Bike {
private String color;
private int topSpeed;
// Main driver method
public static void main(String[] args)
{
// Creating an object of Bike class
Bike Ktm390 = new Bike();
Ktm390.setColor("ORANGE");
Ktm390.setTopSpeed(179);
// Calling bikeInfo() over object of Bike class
Ktm390.bikeInfo();
// Creating an object of KTM class
KTM ktm = new KTM();
ktm.KTM_DEMO();
}
// Methods implementation
// set the maximum speed of bike
public void setTopSpeed(int maxSpeed)
{
this.topSpeed = maxSpeed;
}
// set the color of bike
public void setColor(String color)
{
this.color = color;
}
// print bike information
public void bikeInfo()
{
System.out.println("Bike Color= " + color
+ " Top Speed= " + topSpeed);
}
}
// Child class
class KTM extends Bike {
public void KTM_DEMO()
{
// Creating an object of Engine type
// using engine_kill() method
// KTM_Engine is name of an object
Engine KTM_Engine = new Engine();
KTM_Engine.engine_on();
KTM_Engine.engine_kill();
}
}
class Engine {
// To start the engine
public void engine_on()
{
// Print when engine is turned on
System.out.println("Ignition On..");
}
// To stop the engine
public void engine_kill()
{
// Print when engine is turned off
System.out.println("Ignition killed..");
}
}
Output
Bike Color= ORANGE Top Speed= 179
Ignition On..
Ignition killed..