Q:

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

belongs to collection: Java Inheritance Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 VehicleCar, 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 obj1obj2 of the Vehicle class. But based on initialization, the appropriate run() method gets called and printed messages.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to demonstrate the protected access s... >>
<< Java program to create an employee class by inheri...