The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
![]() |
Home ![]() ![]() |
||
See also: Objects As Return Types | ||
![]() ![]() ![]() ![]() ![]() ![]() ![]() |
||
Objects As Parameters
You can pass objects as parameters in the usual way. For example System.out.println ("(" + p.x + ", " + p.y + ")"); } is a method that takes a point as an argument and prints it in the standard format. If you invoke printPoint (blank), it will print (3, 4). Actually, Java has a built-in method for printing Points. If you invoke System.out.println (blank), you get java.awt.Point[x=3,y=5]This is a standard format Java uses for printing objects. It prints the name of the type, followed by the contents of the object, including the names and values of the instance variables. As a second example, we can rewrite the distance method from Section 5.2 so that it takes two Points as parameters instead of four doubles. public static double distance (Point p1, Point p2) {double dx = (double)(p2.x - p1.x); double dy = (double)(p2.y - p1.y); return Math.sqrt (dx*dx + dy*dy); } The typecasts are not really necessary; I just added them as a reminder that the instance variables in a Point are integers.
|
||
Home ![]() ![]() |