Mutator Methods

AP Computer Science A· difficulty 2/5

public class Age {
    private int years;
    public void setYears(int y) {
        if (y >= 0) years = y;
    }
    public int getYears() { return years; }
}
// ...
Age a = new Age();
a.setYears(-3);
a.setYears(20);
System.out.println(a.getYears());

What is printed?

  • A

    -3

  • B

    20

    check_circle
  • C

    0

  • D

    17

Explanation

The negative value is rejected by the validation guard; setting 20 succeeds.

Want 10 more like this — adaptive to your weak spots?

Related questions