The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

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

## Objects

> A typical Java program creates many objects, which interact with one another by sending each other messages. Through these object interactions, a Java program can implement a GUI, run an animation, or send and receive information over a network. Once an object has completed the work for which it was created, it is garbage-collected and its resources are recycled for use by other objects.

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

> >     public class CreateObjectDemo {
> >         public static void main(String[] args) {

> >             // create a point object and two rectangle objects
> >             Point origin_one = new Point(23, 94);
> >             Rectangle rect_one = new Rectangle(origin_one, 100, 200);
> >             Rectangle rect_two = new Rectangle(50, 100);

> >             // display rect_one's width, height, and area
> >             System.out.println("Width of rect_one: " + rect_one.width);
> >             System.out.println("Height of rect_one: " + rect_one.height);
> >             System.out.println("Area of rect_one: " + rect_one.area());

> >             // set rect_two's position
> >             rect_two.origin = origin_one;

> >             // display rect_two's position
> >             System.out.println("X Position of rect_two: " + rect_two.origin.x);
> >             System.out.println("Y Position of rect_two: " + rect_two.origin.y);

> >             // move rect_two and display its new position
> >             rect_two.move(40, 72);
> >             System.out.println("X Position of rect_two: " + rect_two.origin.x);
> >             System.out.println("Y Position of rect_two: " + rect_two.origin.y);
> >         }
> >     }

> After creating the objects, the program manipulates the objects and displays some information about them.

> This section uses this example to describe the life cycle of an object within a program. From this, you can learn how to write code that creates an object, uses it, and how the system cleans it up.

> - Creating Objects
> - Using Objects
> - Cleaning Up Unused Objects
> - Summary of Creating and Using Objects
> - Questions and Exercises: Creating and Using Objects

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form