Composition In Java

Java


Composition In Java


The composition is the core concept of object-oriented programming. The composition is the design technique to implement a has-a relationship between types of object classes. We can java inheritance or object comparison in java for the code reuse.

Difference between Inheritance and Composition

In Java, inheritance is accurate only when classes are in a relationship. For example cars, trucks, bikes are vehicles and all these vehicles have common features of vehicle class (Superclass) But to represent engine relationships, we have an alternative to inheritance known as composition.
In inheritance, we can derive some functionality to a subclass of the parent class, in the composition a class reuses the functionality by creating a reference to the object of the class.
For ex: A laptop is a composite object containing other objects such as screen, parameter, ram, hard drive, graphics card, optical drive, and keyboard. In other words, the laptop object share has a relationship with other objects. The laptop is a composition that consists of multiple components works together as a team to solve a problem.

Code:
1.
package arduousgeek;
public class Bike 
{
private String color;
private int wheels;
public void bikeFeatures()
{
System.out.println("Bike Color= "+color + " wheels= " + wheels);
}
public void setColor(String color)
{
this.color = color;
}
public void setwheels(int wheels)
{
this.wheels = wheels;
}
}
package arduousgeek;
public class Tvs extends Bike
{
//inherits all properties of Bike class
public void setStart()
{
TvsEngine tvs = new TvsEngine();
tvs.start();
}
}
package arduousgeek;
public class TvsEngine 
{
public void start()
{
System.out.println("Engine has been started.");
}
public void stop()
{
System.out.println("Engine has been stopped.");
}
}
package arduousgeek;
public class Composition 
{
public static void main(String[] args)
{
Tvs tvs = new Tvs();
tvs.setColor("Black");
tvs.setwheels(2);
tvs.bikeFeatures();
tvs.setStart();
}
}
Output:
Bike Color= Black wheels= 2
Engine has been started.
2.
package arduousgeek;

public class Bank 
// concept of Association  
private String name; 
// bank name 
Bank(String name) 
this.name = name; 
}
public String getBankName() 
return this.name; 
}
package arduousgeek;
public class Employee 
{
private String name;
// employee name 
Employee(String name) 
this.name = name; 
}
public String getEmployeeName() 
{
return this.name; 
}
package arduousgeek;
public class Association 
{
public static void main (String[] args) 
Bank bank = new Bank("HSBC"); 
Employee emp = new Employee("ArdousGeek");
System.out.println(emp.getEmployeeName() + 
" is employee of " + bank.getBankName()); 
}
Output:
ArdousGeek is employee of HSBC