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.
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.
Output:
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.