Skip to main content
Engineering LibreTexts

1.4: Objects as Return Types

  • Page ID
  • The java.awt package also provides a class called Rectangle. To use it, you have to import it:

    import java.awt.Rectangle;

    Rectangle objects are similar to points, but they have four attributes: x, y, width, and height. The following example creates a Rectangle object and makes the variable box refer to it:

    Rectangle box = new Rectangle(0, 0, 100, 200);

    Figure 10.4.1 shows the effect of this assignment.

    State diagram showing a Rectangle object.
    Figure \(\PageIndex{1}\): State diagram showing a Rectangle object.

    If you run System.out.println(box), you get:


    Again, println uses the toString method provided by Rectangle, which knows how to display Rectangle objects.

    You can write methods that return objects. For example, findCenter takes a Rectangle as an argument and returns a Point with the coordinates of the center of the rectangle:

    public static Point findCenter(Rectangle box) {
        int x = box.x + box.width / 2;
        int y = box.y + box.height / 2;
        return new Point(x, y);

    The return type of this method is Point. The last line creates a new Point object and returns a reference to it.

    • Was this article helpful?