Interface Implementation in Class Hierarchies


Write a Java program to demonstrate interface implementation in a class hierarchy

  • The Vehicle interface defines a method start() which represents the action of starting a vehicle.
  • The Car and Motorcycle classes implement the Vehicle interface, providing their own implementations of the start() method.
  • In the Main class, instances of Car and Motorcycle are created and assigned to variables of type Vehicle.
  • The start() method is then called on these instances, which invokes the appropriate implementation based on the actual type of the object (polymorphism).

Source Code

interface Vehicle
{
	void start();
}
 
class Car implements Vehicle
{
	@Override
	public void start()
	{
		System.out.println("Car is starting");
	}
}
 
class Motorcycle implements Vehicle
{
	@Override
	public void start()
	{
		System.out.println("Motorcycle is starting");
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		Vehicle car = new Car();
		Vehicle motorcycle = new Motorcycle();
 
		car.start();
		motorcycle.start();
	}
}

Output

Car is starting
Motorcycle is starting

Example Programs