Java Assignment: Inheritance – Vehicle
Management System
Objective:
To understand and implement inheritance in Java by creating a simple system that manages
different types of vehicles using parent and child classes.
Assignment Description:
You are asked to develop a small Java application for a vehicle management system. The
system should have:
1. A base class called Vehicle that contains general properties and behaviors common to all
vehicles.
2. Two subclasses called Car and Motorcycle that inherit from Vehicle and add specific
attributes and behavior.
3. Demonstrate the use of inheritance, method overriding, super keyword, and constructor
chaining.
Requirements:
1. The Vehicle class should include:
- Attributes: brand, year, and color
- Methods: displayInfo()
2. The Car class should:
- Add attribute: numberOfDoors
- Override the displayInfo() method to include car-specific information
3. The Motorcycle class should:
- Add attribute: hasSidecar (boolean)
- Override the displayInfo() method
4. In the main method:
- Create objects of Car and Motorcycle
- Call their methods to demonstrate polymorphism
Solution (with Comments):
// Base class (superclass)
class Vehicle {
String brand;
int year;
String color;
public Vehicle(String brand, int year, String color) {
this.brand = brand;
this.year = year;
this.color = color;
}
public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
System.out.println("Color: " + color);
}
}
// Subclass Car inherits from Vehicle
class Car extends Vehicle {
int numberOfDoors;
public Car(String brand, int year, String color, int numberOfDoors) {
super(brand, year, color);
this.numberOfDoors = numberOfDoors;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Number of Doors: " + numberOfDoors);
}
}
// Subclass Motorcycle inherits from Vehicle
class Motorcycle extends Vehicle {
boolean hasSidecar;
public Motorcycle(String brand, int year, String color, boolean hasSidecar) {
super(brand, year, color);
this.hasSidecar = hasSidecar;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Has Sidecar: " + (hasSidecar ? "Yes" : "No"));
}
}
// Main class to test the inheritance
public class VehicleTest {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 2020, "Red", 4);
System.out.println("=== Car Info ===");
myCar.displayInfo();
Motorcycle myBike = new Motorcycle("Harley-Davidson", 2022, "Black", true);
System.out.println("\n=== Motorcycle Info ===");
myBike.displayInfo();
}
}
Key Concepts Covered:
Concept Description
extends Used to create a subclass that inherits from
a superclass
super() Calls the constructor of the superclass
Method Overriding Subclass provides its own implementation
of a superclass method
Constructor Chaining Calling a superclass constructor from a
subclass
Polymorphism Different implementations of displayInfo()
for different subclasses