Java Inheritance Programming - Create a class called Vehicle with a method called drive(). Create a subclass called Car that overrides the drive() method to print "Repairing a car"
Java Inheritance: Exercise-2 with Solution
Write a Java program to create a class called Vehicle with a method called drive(). Create a subclass called Car that overrides the drive() method to print "Repairing a car".
This program creates a class called 'Vehicle' with a method called drive() and a subclass called Car that overrides the drive() method to print "Repairing a car".
Sample Solution:
Java Code:
// Vehicle.java
// Parent class Vehicle
class Vehicle {
public void drive() {
System.out.println("Repairing a vehicle");
}
}
// Car.java
// Child class Car
class Car extends Vehicle {
@Override
public void drive() {
System.out.println("Repairing a car");
}
}
// Main.java
// Main class
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
Car car = new Car();
vehicle.drive(); // Output: Repairing a vehicle
car.drive(); // Output: Repairing a car
}
}
Sample Output:
Repairing a vehicle Repairing a car
Explanation:
In this program, we first define a parent class called Vehicle with a method called drive() which simply prints " Repairing a vehicle" to the console.
Then, we create a subclass called Car that extends Vehicle and overrides the drive() method to print " Repairing a car" instead.
In the main() method, we create an instance of both the Vehicle and Car classes, and call the drive() method on each object. The output of the first call to drive() will be "Repairing a vehicle", while the output of the second call to drive() will be "Repairing a car", as defined in the Car class.
Flowchart:



Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Animal with a method called makeSound.
Next: Create a class called Shape with a method called getArea and a subclass called Rectangle.
What is the difficulty level of this exercise?
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join