Model a Computer that HAS-A Cpu, Ram and Storage (composition, not inheritance); compute its total price and power draw, and upgrade the RAM by replacing the part.
Solution
Main.java
class Part {
protected final String model;
protected final int price, watts;
Part(String model, int price, int watts) { this.model = model; this.price = price; this.watts = watts; }
@Override public String toString() { return model; }
}
class Cpu extends Part { Cpu(String m, int p, int w) { super(m, p, w); } }
class Ram extends Part {
final int gb;
Ram(int gb, int price) { super(gb + "GB DDR5", price, gb / 4); this.gb = gb; }
}
class Storage extends Part { Storage(String m, int p) { super(m, p, 5); } }
class Computer { // HAS-A parts
private final Cpu cpu;
private Ram ram;
private final Storage storage;
Computer(Cpu cpu, Ram ram, Storage storage) { this.cpu = cpu; this.ram = ram; this.storage = storage; }
void upgradeRam(Ram bigger) { if (bigger.gb > ram.gb) ram = bigger; }
int price() { return cpu.price + ram.price + storage.price; }
int watts() { return cpu.watts + ram.watts + storage.watts; }
@Override public String toString() { return cpu + " / " + ram + " / " + storage + " = Rs " + price() + ", " + watts() + "W"; }
}
public class Main {
public static void main(String[] args) {
Computer pc = new Computer(new Cpu("Ryzen 7 7700", 27000, 65), new Ram(16, 5000), new Storage("1TB NVMe", 6500));
System.out.println(pc);
pc.upgradeRam(new Ram(8, 2500));
pc.upgradeRam(new Ram(32, 9500));
System.out.println(pc);
}
}
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!