Write an abstract SmartDevice (name, on/off, power use) with abstract status() and a concrete energyUsed(hours); implement Light (dimmable) and AirConditioner (temperature affects power), switch some on and print a home energy report.
Solution
Main.java
import java.util.List;
abstract class SmartDevice {
protected final String name;
protected boolean on;
protected SmartDevice(String name) { this.name = name; }
void turnOn() { on = true; }
void turnOff() { on = false; }
protected abstract double watts();
protected abstract String status();
double energyUsed(double hours) { return on ? watts() * hours / 1000 : 0; } // kWh
String line(double hours) { return String.format("%-12s %-22s %5.2f kWh", name, on ? status() : "off", energyUsed(hours)); }
}
class Light extends SmartDevice {
private int brightness = 100;
Light(String n) { super(n); }
void dim(int pct) { brightness = Math.max(10, Math.min(100, pct)); }
protected double watts() { return 12 * brightness / 100.0; }
protected String status() { return "on, " + brightness + "%"; }
}
class AirConditioner extends SmartDevice {
private int temp = 24;
AirConditioner(String n) { super(n); }
void setTemp(int t) { temp = Math.max(16, Math.min(30, t)); }
protected double watts() { return 1500 + (24 - temp) * 100; }
protected String status() { return "on, " + temp + "°C"; }
}
public class Main {
public static void main(String[] args) {
Light hall = new Light("Hall light"), bed = new Light("Bed lamp");
AirConditioner ac = new AirConditioner("Bedroom AC");
hall.turnOn(); hall.dim(50);
ac.turnOn(); ac.setTemp(20);
List<SmartDevice> home = List.of(hall, bed, ac);
double total = 0;
for (SmartDevice d : home) { System.out.println(d.line(8)); total += d.energyUsed(8); }
System.out.printf("total %.2f kWh%n", total);
}
}
Output Verified by compiling and running
Hall light on, 50% 0.05 kWh
Bed lamp off 0.00 kWh
Bedroom AC on, 20°C 15.20 kWh
total 15.25 kWh
The base class handles on/off and energy maths; each device only defines its power draw and status text. AC: 1500 + 4 × 100 = 1900 W × 8 h = 15.2 kWh.
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!