CH10 – Objects as Return Types

  1. Create a new class named ObjectAsReturnType.
  2. Import java.awt.Rectangle, java.awt.Point, and add a main method.
import java.awt.Rectangle;
import java.awt.Point;
public class ObjectAsReturnType{
  public static void main(String[] args){
  }
}
  1. Create a new method named findCenter that takes a Rectangle as a parameter and returns a Point.
public static Point findCenter(Rectangle box){
  int x = box.x + box.width / 2;
  int y = box.y + box.height / 2;
  Point retPoint = new Point(x,y);
  return retPoint;
}
  1. Add the following code to main.
Rectangle box = new Rectangle(0,0,100,200);
Point myPoint = ObjectAsReturnType.findCenter(box);
System.out.println(box.toString());
System.out.println(myPoint.toString());
  1. Compile and run the program.
$ javac ObjectAsReturnType.java 
$ java ObjectAsReturnType
java.awt.Rectangle[x=0,y=0,width=100,height=200]
java.awt.Point[x=50,y=100]

The complete class should appear as follows.

import java.awt.Rectangle;
import java.awt.Point;
public class ObjectAsReturnType{
  public static void main(String[] args){
    Rectangle box = new Rectangle(0,0,100,200);
    Point myPoint = ObjectAsReturnType.findCenter(box);
    System.out.println(box.toString());
    System.out.println(myPoint.toString());
  }
  public static Point findCenter(Rectangle box){
    int x = box.x + box.width / 2;
    int y = box.y + box.height / 2;
    Point retPoint = new Point(x,y);
    return retPoint;
  }
}