Subclass Method Overrides Superclass Method and Uses super Keyword In Java


Write a Java program to demonstrate method overriding with a subclass that overrides a method and calls the superclass method using the super keyword

The code defines a hierarchy of classes in Java, with a Vehicle class and a Car class. It demonstrates method overriding and the use of the super keyword. Here's an explanation of the code:

  • Vehicle is the base class with a method start(). When this method is called, it prints "Vehicle starting..." to the console.
  • Car is a subclass of Vehicle. It overrides the start() method from the Vehicle class using the @Override annotation. In the overridden method, it first calls the start() method of the superclass using super.start(), and then it prints "Car starting..." to the console.
  • In the Main class, you create an instance of the Car class named car.
  • You call the start() method on the car object using car.start(). Since Car is a subclass of Vehicle and it has overridden the start method, it will call the overridden start method from the Car class. The overridden method first calls the start method from the superclass (using super.start()), and then it prints "Car starting..." to the console.

Source Code

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

Output

Vehicle starting...
Car starting...