Write a Java program to Override a base class method into a derived class


This Java program demonstrates method overriding, a concept in object-oriented programming where a child class provides a specific implementation of a method that is already defined in its parent class. In this program, there are two classes: Vehicle and Car. The display method in the Car class overrides the display method in the Vehicle class. Here's an explanation of the program:

  • public class OverrideMethod: 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 the starting point of the program. It creates an object of the Car class and demonstrates method overriding by calling the display method on this object.
  • Car car = new Car();: This line creates an object of the Car class. The display method that will be called on this object is the one defined in the Car class.
  • car.display();: This line calls the display method on the Car object. Due to method overriding, the display method in the Car class is executed instead of the one in the Vehicle class.
  • class Vehicle: This is the base class (superclass) that represents generic vehicle properties and behaviors.
  • void display(): The display method in the Vehicle class prints a message indicating that it is a vehicle.
  • class Car extends Vehicle: This is the derived class (subclass) that inherits from the Vehicle class. It represents a specific type of vehicle, a car.
  • @Override: This annotation is used to explicitly indicate that the display method in the Car class is meant to override a method with the same name in the parent class. While not required, it's a good practice to use this annotation to make the code more readable and to ensure that you're correctly overriding a method from the parent class.
  • void display(): The display method in the Car class provides a specific implementation that prints a message indicating that it is a car. This method overrides the display method from the Vehicle class.

This program demonstrates method overriding, where the Car class provides its own implementation of the display method, which replaces the one inherited from the Vehicle class. When the display method is called on a Car object, the overridden method in the Car class is executed, and it prints "This is a Car." This allows child classes to provide specific behavior while still inheriting some common behavior from their parent classes.


Source Code

public class OverrideMethod		// Main class
{
	public static void main(String[] args)
	{        
		Car car = new Car();	// Create an object of the derived class       
		car.display();		 // Call the overridden method
	}
}
class Vehicle	// Base class
{
	void display()
	{
		System.out.println("This is a Vehicle");
	}
}
class Car extends Vehicle	// Derived class
{
	@Override
	void display()
	{
		System.out.println("This is a Car");
	}
}

Output

This is a Car