LearnFrenzy
Sign in Take a free test

Inheritance · Inheritance Programs · Question 7

Composition: building a computer from parts in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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);
    }
}

Output Verified by compiling and running

Ryzen 7 7700 / 16GB DDR5 / 1TB NVMe = Rs 38500, 74W
Ryzen 7 7700 / 32GB DDR5 / 1TB NVMe = Rs 43000, 78W

The parts use inheritance (a Cpu IS-A Part); the Computer uses composition (it HAS parts), which lets one part be swapped without changing the others.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links