The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

The Life Cycle of an Object

A typical Java program creates many objects, which as you know, interact by sending messages (in the Learning the Java Language trail) . Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects.

Here's a small program, called CreateObjectDemo (in a .java source file), that creates three objects: one Point (in a .java source file) object and two Rectangle (in a .java source file) objects. You will need all three source files to compile this program.

public class CreateObjectDemo {
	public static void main(String[] args) {
		// declare and create a point object
		// and two rectangle objects
		Point originOne = new Point(23, 94);
		Rectangle rectOne = new Rectangle(originOne, 100, 200);
		Rectangle rectTwo = new Rectangle(50, 100);
		// display rectOne's width, height, and area
		System.out.println("Width of rectOne: " +
			rectOne.width);
		System.out.println("Height of rectOne: " +
			rectOne.height);
		System.out.println("Area of rectOne: " + rectOne.area());
		// set rectTwo's position
		rectTwo.origin = originOne;
		// display rectTwo's position
		System.out.println("X Position of rectTwo: "
			+ rectTwo.origin.x);
		System.out.println("Y Position of rectTwo: "
		+ rectTwo.origin.y);
		// move rectTwo and display its new position
		rectTwo.move(40, 72);
		System.out.println("X Position of rectTwo: "
			+ rectTwo.origin.x);
		System.out.println("Y Position of rectTwo: "
			+ rectTwo.origin.y);
	}
}
This program creates, manipulates, and and displays information about various objects. Here's the output:
Width of rectOne: 100
Height of rectOne: 200
Area of rectOne: 20000
X Position of rectTwo: 23
Y Position of rectTwo: 94
X Position of rectTwo: 40
Y Position of rectTwo: 72

The following sections use the above example to describe the life cycle of an object within a program. From them, you will learn how to write code that creates and uses objects in your own programs. You will also learn how the system cleans up after an object after its life has ended.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.