Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1) Suppose you were given the job to write a Java class to run a stoplight to co

ID: 638637 • Letter: 1

Question

1) Suppose you were given the job to write a Java class to run a stoplight to control traffic at an intersection. The state of the stoplight is the color of the light currently being shown (red, green or yellow) and the behavior of the stoplight is that the light is displayed for people to see and that the light changes color under certain conditions. Given the following public interface, write the Java code that goes with each method. Which of these methods are accessors and which are mutators?

2) Write a short test program that tests the StopLight class you implemented above. Your short program should create a new StopLight and then cycle through a number of light changes, checking the result after each change.

Explanation / Answer

StopLight.java

public interface Stoplight {
   
   public String getColor();
     


   public void changeColor();
   

StoplightImpl.java

public class StoplightImpl implements Stoplight{


  private int currentColor;


  public StoplightImpl() {
   this.currentColor = 2;
}


  public String getColor(){
   if(1 == this.currentColor)
    return "YELLOW";
   if(2== this.currentColor)
   return "RED";
   if(0 == this.currentColor)
    return "GREEN";


   return "NO COLOR";
  }
    public void changeColor(){
      if(0 == this.currentColor){
       this.currentColor = 1;
       return;
      }
      if(1 == this.currentColor){
       this.currentColor = 2;
       return;
      }
      if(2 == this.currentColor){
       this.currentColor = 0;
       return;
      }
    }
}