Java Assignment: Exploring
Polymorphism
Objectives
- Understand method overloading and overriding.
- Apply 'final' keyword to prevent method/variable overriding.
- Demonstrate use of 'protected' access modifier.
- Implement upcasting to access subclass objects via superclass reference.
Instructions
Write a Java program that simulates a simple Vehicle Management System using
polymorphism. Implement the following:
Class Definitions
1. Base Class: Vehicle
public class Vehicle {
protected String brand;
public Vehicle(String brand) {
this.brand = brand;
}
public void displayInfo() {
System.out.println("Vehicle Brand: " + brand);
}
// Overloaded methods
public void service() {
System.out.println("Generic vehicle service.");
}
public void service(String serviceType) {
System.out.println("Vehicle service: " + serviceType);
}
// final method
public final void fuelType() {
System.out.println("Uses petrol or diesel.");
}
}
2. Subclass: Car
public class Car extends Vehicle {
private String model;
public Car(String brand, String model) {
super(brand);
this.model = model;
}
@Override
public void displayInfo() {
System.out.println("Car Brand: " + brand + ", Model: " + model);
}
public void honk() {
System.out.println("Car horn: Beep Beep!");
}
}
3. Subclass: Truck
public class Truck extends Vehicle {
private int capacity;
public Truck(String brand, int capacity) {
super(brand);
this.capacity = capacity;
}
@Override
public void displayInfo() {
System.out.println("Truck Brand: " + brand + ", Capacity: " + capacity + " tons");
}
}
Main Class
public class Main {
public static void main(String[] args) {
Vehicle v1 = new Car("Toyota", "Corolla");
Vehicle v2 = new Truck("Volvo", 10);
v1.displayInfo();
v2.displayInfo();
v1.fuelType();
v1.service();
v1.service("Full Service");
if (v1 instanceof Car) {
Car c = (Car) v1;
c.honk();
}
}
}
Tasks for the Student
1. Explain the difference between overloading and overriding in your own words.
2. Modify the Truck class to include a new protected variable driverName, and add a
method to display it.
3. Add one more subclass, Motorbike, and override the displayInfo method.
4. Try to override the fuelType() method in any subclass and observe the result.
5. Add a method in Main that accepts a Vehicle parameter and calls displayInfo() —
demonstrate polymorphism in action.
Deliverables
- Source code (.java files)
- Answers to theory questions (Word or PDF)