Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Vehicle {
- // Protected attributes can be accessed by subclasses
- protected String brand;
- protected int year;
- // Constructor
- public Vehicle(String brand, int year) {
- this.brand = brand;
- this.year = year;
- }
- // Method to display vehicle details
- public void displayInfo() {
- System.out.println("Brand: " + brand);
- System.out.println("Year: " + year);
- }
- // Method to get the type of vehicle (can be overridden)
- public String getType() {
- return "Generic Vehicle";
- }
- }
- // Subclass Car
- class Car extends Vehicle {
- private int numDoors;
- // Constructor
- public Car(String brand, int year, int numDoors) {
- super(brand, year); // Call to the superclass constructor
- this.numDoors = numDoors;
- }
- // Overriding displayInfo method
- @Override
- public void displayInfo() {
- super.displayInfo(); // Call to superclass method
- 18
- System.out.println("Number of Doors: " + numDoors);
- }
- // Overriding getType method
- @Override
- public String getType() {
- return "Car";
- }
- }
- // Subclass Truck
- class Truck extends Vehicle {
- private double loadCapacity;
- // Constructor
- public Truck(String brand, int year, double loadCapacity) {
- super(brand, year); // Call to the superclass constructor
- this.loadCapacity = loadCapacity;
- }
- // Overriding displayInfo method
- @Override
- public void displayInfo() {
- super.displayInfo(); // Call to superclass method
- System.out.println("Load Capacity: " + loadCapacity + " tons");
- }
- // Overriding getType method
- @Override
- public String getType() {
- return "Truck";
- }
- }
- // Main class to demonstrate the hierarchy
- public class VehicleDemo {
- public static void main(String[] args) {
- // Create instances of Car and Truck
- Vehicle myCar = new Car("Toyota", 2020, 4);
- 19
- Vehicle myTruck = new Truck("Ford", 2018, 2.5);
- // Display vehicle information
- System.out.println("Vehicle Type: " + myCar.getType());
- myCar.displayInfo();
- System.out.println("-------------------------");
- System.out.println("Vehicle Type: " + myTruck.getType());
- myTruck.displayInfo();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement