Advertisement
GamerBhai02

heirarchy of vehicles

Nov 11th, 2024
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | Source Code | 0 0
  1. class Vehicle {
  2.  // Protected attributes can be accessed by subclasses
  3.  protected String brand;
  4.  protected int year;
  5.  // Constructor
  6.  public Vehicle(String brand, int year) {
  7.  this.brand = brand;
  8.  this.year = year;
  9.  }
  10.  // Method to display vehicle details
  11.  public void displayInfo() {
  12.  System.out.println("Brand: " + brand);
  13.  System.out.println("Year: " + year);
  14.  }
  15.  // Method to get the type of vehicle (can be overridden)
  16.  public String getType() {
  17.  return "Generic Vehicle";
  18.  }
  19. }
  20. // Subclass Car
  21. class Car extends Vehicle {
  22.  private int numDoors;
  23.  // Constructor
  24.  public Car(String brand, int year, int numDoors) {
  25.  super(brand, year); // Call to the superclass constructor
  26.  this.numDoors = numDoors;
  27.  }
  28.  // Overriding displayInfo method
  29.  @Override
  30.  public void displayInfo() {
  31.  super.displayInfo(); // Call to superclass method
  32. 18
  33.  System.out.println("Number of Doors: " + numDoors);
  34.  }
  35.  // Overriding getType method
  36.  @Override
  37.  public String getType() {
  38.  return "Car";
  39.  }
  40. }
  41. // Subclass Truck
  42. class Truck extends Vehicle {
  43.  private double loadCapacity;
  44.  // Constructor
  45.  public Truck(String brand, int year, double loadCapacity) {
  46.  super(brand, year); // Call to the superclass constructor
  47.  this.loadCapacity = loadCapacity;
  48.  }
  49.  // Overriding displayInfo method
  50.  @Override
  51.  public void displayInfo() {
  52.  super.displayInfo(); // Call to superclass method
  53.  System.out.println("Load Capacity: " + loadCapacity + " tons");
  54.  }
  55.  // Overriding getType method
  56.  @Override
  57.  public String getType() {
  58.  return "Truck";
  59.  }
  60. }
  61. // Main class to demonstrate the hierarchy
  62. public class VehicleDemo {
  63.  public static void main(String[] args) {
  64.  // Create instances of Car and Truck
  65.  Vehicle myCar = new Car("Toyota", 2020, 4);
  66. 19
  67.  Vehicle myTruck = new Truck("Ford", 2018, 2.5);
  68.  // Display vehicle information
  69.  System.out.println("Vehicle Type: " + myCar.getType());
  70.  myCar.displayInfo();
  71.  System.out.println("-------------------------");
  72.  System.out.println("Vehicle Type: " + myTruck.getType());
  73.  myTruck.displayInfo();
  74.  }
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement