// class representing a robot // example of inheriting and implementing several interfaces package interfaceexample; public class Robot extends Machine implements Fighter, Worker, NoiseMaker { protected String designation; protected int power; // constructors public Robot() { super(); this.designation = "Mr. Roboto"; this.power = 100; } public Robot(String designation, int power) { this(); this.setDesignation(designation); this.setPower(power); } // accessors, mutators public int getPower() { return power; } // power determines whether robot is on public void setPower(int power) { // take negative to mean zero // turn off if (power <= 0) { power = 0; deactivate(); } this.power = power; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } // behaviors // make a beepy noise public void beep() { if (getOn()) { System.out.println(getDesignation()+ " goes BEEP"); } } // attack with lasers // for interface Fighter public void attack() { if (!getOn()) {return;} // I am a bad person System.out.println(getDesignation()+ " shoots lasers from where its eyes would be if it had eyes instead of deadly lasers PEW-PEW!"); // drains lots of battery power setPower(getPower() - 5); } // defend self with forcefield // for interface Fighter public void defend() { if (getOn()) { System.out.println(getDesignation()+ " turns on its forcefield"); // drains some battery power setPower(getPower() - 3); } } // move boxes around public void moveBoxes() { if (getOn()) { System.out.println(getDesignation()+ " moves boxes"); // drains some battery power setPower(getPower() - 2); } } // just a wrapper around moveBoxes // so we can qualify as a Worker public void doWork() { moveBoxes(); } // just a wrapper around beep // so we can qualify as a NoiseMaker public void makeNoise() { beep(); } // turn on the robot public void activate() { if (getPower() > 0){ setOn(true); }else { System.out.println(getDesignation() + "'s batteries are dead."); } } // turn off the robot public void deactivate() { setOn(false); } // utilities public String toString() { String str = "Robot designation: " + getDesignation() + " power level: " + getPower(); if (getOn()) { return str + " (ON)"; } return str + (" (OFF)"); } // equal if all three instance variables equal public boolean equals(Object obj) { if (obj != null && obj instanceof Robot) { Robot other = (Robot) obj; // short circuit eval means java only does second clause // if first clause evaluated to false // in this case, designation is null, so use == boolean namesame = (this.getDesignation() != null && this.getDesignation().equals(other.getDesignation()) ) || this.getDesignation() == other.getDesignation() ; return namesame && this.power == other.power && this.on == other.on; } return false; } }