1.3: Objects as Parameters
- Page ID
- 15272
You can pass objects as parameters in the usual way. For example:
public static void printPoint(Point p) { System.out.println("(" + p.x + ", " + p.y + ")"); }
This method takes a point as an argument and displays its attributes in parentheses. If you invoke printPoint(blank)
, it displays (3, 4)
.
But we don’t really need a method like printPoint
, because if you invoke System.out.println(blank)
you get:
java.awt.Point[x=3,y=4]
Point
objects provide a method called toString
that returns a string representation of a point. When you call println
with objects, it automatically calls toString
and displays the result. In this case, it shows the name of the type (java.awt.Point
) and the names and values of the attributes.
As another example, we can rewrite the distance
method from Section 6.2 so that it takes two Point
s as parameters instead of four double
s.
public static double distance(Point p1, Point p2) { int dx = p2.x - p1.x; int dy = p2.y - p1.y; return Math.sqrt(dx * dx + dy * dy); }
Passing objects as parameters makes the source code more readable and less error-prone, because related values are bundled together.