LearnFrenzy
Sign in Take a free test

Encapsulation · Predict the Output · Question 9

Encapsulated state with intention-revealing methods Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

What is the output of the following Java program?

Main.java
class Subscription {
    private boolean active;
    private int monthsPaid;

    public void pay(int months) { if (months > 0) { monthsPaid += months; active = true; } }
    public void cancel() { active = false; }
    public boolean isActive() { return active; }
    public int getMonthsPaid() { return monthsPaid; }
}

public class Main {
    public static void main(String[] args) {
        Subscription s = new Subscription();
        boolean a = s.isActive();
        s.pay(3);
        s.pay(-1);
        boolean b = s.isActive();
        s.cancel();
        System.out.println(a + " " + b + " " + s.isActive() + " " + s.getMonthsPaid());
    }
}
  • A false true false 3 Correct
  • B false true false 2
  • C true true false 3
  • D false false false 3
Correct Answer: Option A

pay(-1) is ignored; cancel turns the subscription off without losing the payment history.

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