ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.