Write a Java program to Method Overloading and Inheritance


This Java program demonstrates method overloading, a concept in object-oriented programming where a class can have multiple methods with the same name but different parameter lists. In this program, there are two classes: Vehicle (the parent class) and Car (the child class), and the Car class overloads the start method. Here's an explanation of the program:

  • public class MethodOverloading: This is the main class that contains the main method, the entry point of the program.
  • public static void main(String[] args) : The main method is where the program execution starts. It creates an object of the Car class and demonstrates method overloading by calling two different versions of the start method.
  • Car car = new Car();: This line creates an object of the Car class.
  • car.start();: This line calls the start method on the car object. Since the Car class does not override the start method of the parent class, the method from the parent class (Vehicle) is called. The output will be "Vehicle starting ..."
  • car.start(3); : This line calls the overloaded start method in the Car class, which takes an integer parameter. This version of the method prints a message indicating the number of cars starting. The output will be "Starting 3 Cars ..."
  • class Vehicle: This is the parent class, which has a method named start.
  • void start(): The start method of the Vehicle class simply prints "Vehicle starting ..."
  • class Car extends Vehicle: This is the child class that inherits from the Vehicle class.
  • void start(int count): The Car class overloads the start method by defining a new version that takes an integer parameter, count. This version of the method prints a message indicating the number of cars starting.

This program demonstrates method overloading, where the child class (Car) defines a method with the same name as the one in the parent class (Vehicle) but with a different parameter list. The appropriate version of the method is called based on the number and types of arguments provided when the method is invoked.


Source Code

public class MethodOverloading	// Main class
{
	public static void main(String[] args)
	{
		Car car = new Car();
		car.start();  	// Accessing parent class method
		car.start(3); 	// Accessing overloaded method in child class
	}
}
class Vehicle	// Parent class
{
	void start()
	{
		System.out.println("Vehicle starting ...");
	}
}
class Car extends Vehicle	// Child class
{
	void start(int count)
	{
		System.out.println("Starting " + count + " Cars ...");
	}
}

Output

Vehicle starting ...
Starting 3 Cars ...