More about Objects and Classes
8. Program that uses the toString() Method
Answer:
A parameter is an item of data supplied to a method or a constructor.
Program that uses the toString()
Method
toString()
Method
import java.awt.*;class PointEg2{public static void main ( String arg[] ) { Point a, b, c; // reference variables a = new Point(); // create a Point at ( 0, 0); // save the reference in "a" b = new Point( 12, 45 ); // create a Point at (12, 45); // save the reference in "b" c = new Point( b ); // create a Point String strA = a.toString(); // create a String object based on the data // found in the object referenced by "a". System.out.println( strA ); } } |
toString()
needs no parameters. However, use empty parentheses when the method is called. The example program shows this.
When this program runs, the statement:
String strA = a.toString();
creates a String
object based on the data in the object referred to by a
. The strA
refers to this new String
object. Then the characters from the String
are sent to the monitor with println
.
The program prints out:
java.awt.Point[x=0,y=0]
The Point
object has not been altered: it still exists and is referred to by a
.
Question 8:
Just as the program is about to end, how many objects have been created? Has any garbage been created?