Java program to override a base class method into a derived class

Learn how to override a base class method into a derived class in Java?
Submitted by Nidhi, on March 24, 2022

Problem Solution:

In this program, we will 2 classes Vehicle and Car. Both classes contains run() method. The run() method is overridden in the Car class.

Method Overriding:

If a subclass and superclass have the same methods. Then it is known as method overriding in Java.

Program/Source Code:

The source code to override a base class method into the derived class is given below. The given program is compiled and executed successfully.

// Java program to override a base class method 
// into a derived class

class Vehicle {
  void run() {
    System.out.println("Vehicle is running.");
  }
}

class Car extends Vehicle {
  void run() {
    System.out.println("Car is running.");
  }
}

public class Main {
  public static void main(String[] args) {
    Vehicle obj1 = new Car();
    obj1.run();

    Vehicle obj2 = new Vehicle();
    obj2.run();
  }
}

Output:

Car is running.
Vehicle is running.

Explanation:

In the above program, we created 3 classes Vehicle, Car, and Main(). The Vehicle and Car, both classes contain run() method. Here, we override method run() by inheriting Vehicle class into Car class.

The Main class contains a method main(). The main() method is the entry point for the program, here we created the references obj1, obj2 of the Vehicle class. But based on initialization, the appropriate run() method gets called and printed messages.

Java Inheritance Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.