LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 14

Allowed and refused state transitions Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

What is the output of the following Java program?

Main.java
class Ticket {
    private String state = "OPEN";

    boolean start()   { return move("OPEN", "IN_PROGRESS"); }
    boolean resolve() { return move("IN_PROGRESS", "RESOLVED"); }
    boolean reopen()  { return move("RESOLVED", "OPEN"); }

    private boolean move(String from, String to) {
        if (!state.equals(from)) return false;
        state = to;
        return true;
    }

    String state() { return state; }
}

public class Main {
    public static void main(String[] args) {
        Ticket t = new Ticket();
        System.out.println(t.resolve() + " " + t.start() + " " + t.start() + " " + t.resolve() + " " + t.reopen() + " " + t.state());
    }
}
  • A false true false true true OPEN Correct
  • B true true true true true OPEN
  • C false true false true false RESOLVED
  • D false false false false false OPEN
Correct Answer: Option A

Each action succeeds only from its allowed starting state.

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