Build a three-level hierarchy Vehicle → Car → ElectricCar, each adding fields and extending describe() with super.describe(); show the constructor chain and the final description.
Solution
Main.java
class Vehicle {
protected final String brand;
Vehicle(String brand) { this.brand = brand; System.out.println("Vehicle ready"); }
String describe() { return brand; }
}
class Car extends Vehicle {
protected final int seats;
Car(String brand, int seats) { super(brand); this.seats = seats; System.out.println("Car ready"); }
@Override String describe() { return super.describe() + ", " + seats + " seats"; }
}
class ElectricCar extends Car {
private final int rangeKm;
private int chargePct = 100;
ElectricCar(String brand, int seats, int rangeKm) { super(brand, seats); this.rangeKm = rangeKm; System.out.println("ElectricCar ready"); }
void drive(int km) { chargePct = Math.max(0, chargePct - km * 100 / rangeKm); }
@Override String describe() { return super.describe() + ", range " + rangeKm + " km, charge " + chargePct + "%"; }
}
public class Main {
public static void main(String[] args) {
ElectricCar ev = new ElectricCar("Tata Nexon EV", 5, 465);
ev.drive(93);
ev.drive(140);
System.out.println(ev.describe());
}
}
Output Verified by compiling and running
Vehicle ready
Car ready
ElectricCar ready
Tata Nexon EV, 5 seats, range 465 km, charge 50%
93 km uses 20% and 140 km uses 30% (integer division). Each describe() adds its own detail to its parent's.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!