Composition (OOP)

Topic Progress

With inheritance a dog is an animal

With composition a computer has an operating system, has a power supply

Create a new Java Project in either Eclipse or Netbeans (Eclipse shown here)

  1. Add the code as below, run test and debug

  2. Add a class Printer with methods “start printing”, “pause printing” and “stop printing”
  3. Add another class of your choice (scanner, mouse, projector…..) and add methods, test and run
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Computer{
      private OperatingSystem os = new OperatingSystem();
      private PowerSupply ps = new PowerSupply();
   
      Computer() {
          ps.turnOn();
          os.bootUp();
 
         
      }
      void allDone() {
          os.shutDown();
          ps.turnOff();
      }
 }


1
2
3
4
class OperatingSystem {
      void bootUp() { System.out.println("Boot up"); }
      void shutDown() {System.out.println("Shut down"); }
 }


1
2
3
4
class PowerSupply {
      void turnOn() {  System.out.println("Turned on");}
      void turnOff() {System.out.println("Turned off"); }
 }


1
2
3
4
5
6
7
8
class TestMe {
      public static void main(String args[]){
          Computer c = new Computer();
          // use computer...
          c.allDone();
         
      }
 }