Java Reference
In-Depth Information
The following example demonstrates a class invariant. A
Rectangle
object is not
considered valid if either its
width
or
height
is negative. Examine the following
Rectangle
class, and assuming assertions are turned on, determine the output of running the
main
method:
1. public class Rectangle {
2. private int width, height;
3.
4. public Rectangle(int width, int height) {
5. this.width = width;
6. this.height = height;
7. }
8.
9. public int getArea() {
10. assert isValid() : “Not a valid Rectangle”;
11. return width * height;
12. }
13.
14. private boolean isValid() {
15. return (width >= 0 && height >= 0);
16. }
17.
18. public static void main(String [] args) {
19. Rectangle one = new Rectangle(5,12);
20. Rectangle two = new Rectangle(-4,10);
21. System.out.println(“Area one = “ + one.getArea());
22. System.out.println(“Area two = “ + two.getArea());
23. }
24.}
The
isValid
method is an example of a class invariant. It is a private method that
tests the state of the object. Line 10 invokes
isValid
in an assertion statement before
computing the area. Within
main
,
Rectangle
one
is valid and its area is output.
Rectangle
two
has a negative
width
so the assertion fails on line 10. The output is shown here:
Area one = 60
Exception in thread “main” java.lang.AssertionError: Not a valid Rectangle
at Rectangle.getArea(Rectangle.java:10)
at Rectangle.main(Rectangle.java:22)
Search WWH ::
Custom Search