public class Car
{
private String color;
private int maxSpeed;
public Car(String color, int maxSpeed)
{
super();
this.color = color;
this.maxSpeed = maxSpeed;
}
public String getColor()
{
return color;
}
public void setColor(String color)
{
this.color = color;
}
public int getMaxSpeed()
{
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed)
{
this.maxSpeed = maxSpeed;
}
public void carInfo()
{
System.out.println("Car Color= " + color + ", Max Speed= " + maxSpeed);
}
}
Engine.java public class Engine
{
public void start()
{
System.out.println("Engine Started:");
}
public void stop()
{
System.out.println("Engine Stopped:");
}
}
MarutiSwift.java /**
*
* MarutiSwift is specific type of Car which extends Car class means MarutiSwift
* IS-A Car.
*
* MarutiSwift extends Car and thus inherits all properties and methods from Car
* (except final and static).
*
* MarutiSwift can also define all its specific functionality.
*/
public class MarutiSwift extends Car
{
/*
* MarutiSwift HAS-A Engine
*/
private Engine engine;
public MarutiSwift(String color, int maxSpeed, Engine engine)
{
super(color, maxSpeed);
this.engine = engine;
}
public void startMarutiSwift()
{
engine.start();
}
}
RelationshipDemo.java /**
* RelationsDemo class is making object of MarutiSwift class and initialized it.
* Though MarutiSwift class does not have setColor(), setMaxSpeed() and carInfo()
* methods still we can use it due to IS-A relationship of MarutiSwift class with Car
* class.
*/
public class RelationshipDemo
{
public static void main(String[] args)
{
Engine engine = new Engine();
MarutiSwift marutiSwift = new MarutiSwift("Red", 200, engine);
marutiSwift.carInfo();
marutiSwift.startMarutiSwift();
}
}