Advertisement
GamerBhai02

4. Vehicle Hierarchy

Jan 16th, 2025
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.51 KB | Source Code | 0 0
  1. class Vehicle{
  2.     private String brand;
  3.     private int year;
  4.     public Vehicle(String brand,int year){
  5.         this.brand = brand;
  6.         this.year = year;
  7.     }
  8.     public void displayInfo(){
  9.         System.out.println("Brand: "+brand);
  10.         System.out.println("Year: "+year);
  11.     }
  12.     public String getType(){
  13.         return "Generic Vehicle";
  14.     }
  15. }
  16. class Car extends Vehicle{
  17.     private int numDoor;
  18.     public Car(String brand,int year,int numDoor){
  19.         super(brand,year);
  20.         this.numDoor = numDoor;
  21.     }
  22.     public void displayInfo(){
  23.         super.displayInfo();
  24.         System.out.println("Number of Doors: "+numDoor);
  25.     }
  26.     public String getType(){
  27.         return "Car";
  28.     }
  29. }
  30. class Truck extends Vehicle{
  31.     private double loadCapacity;
  32.     public Truck(String brand,int year,double loadCapacity){
  33.         super(brand,year);
  34.         this.loadCapacity = loadCapacity;
  35.     }
  36.     public void displayInfo(){
  37.         super.displayInfo();
  38.         System.out.println("Load Capacity: "+loadCapacity+" Ton");
  39.     }
  40.     public String getType(){
  41.         return "Truck";
  42.     }
  43. }
  44. public class VehicleHierarchy{
  45.     public static void main(String[] args){
  46.         Vehicle car = new Car("Honda",1986,4);
  47.         Vehicle truck = new Truck("Benz",1999,20);
  48.         System.out.println("Vehicle Type: "+car.getType());
  49.         car.displayInfo();
  50.         System.out.print("\n");
  51.         System.out.println("Vehicle Type: "+truck.getType());
  52.         truck.displayInfo();
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement