← Unit 3 · all exercises
Saved in this browser only

A setter that refuses bad values

Write an Age class. setAge stores the value, but only when it is zero or more — a negative value leaves the age unchanged. The constructor starts the age at 0, and getAge returns it.

class Age { Age(); void setAge(int value); int getAge(); }

Age.java
Loading editor…
Results

Examples

  • Age a = new Age(); a.setAge(21); a.getAge() → 21
  • Age a = new Age(); a.setAge(-5); a.getAge() → 0the bad value is ignored

There are also 3 hidden tests you can't see. Solve the problem, not the examples.