Documentation

The Java™ Tutorials
Hide TOC
Objects对象
Trail: Learning the Java Language
Lesson: Classes and Objects

Objects对象

A typical Java program creates many objects, which as you know, interact by invoking methods.一个典型的Java程序创建许多对象,正如您所知,这些对象通过调用方法进行交互。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.通过这些对象交互,程序可以执行各种任务,例如实现GUI、运行动画或通过网络发送和接收信息。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, that creates three objects: one Point object and two Rectangle objects.这是一个名为CreateObjectDemo的小程序,它创建三个对象:一个Point对象和两个Rectangle对象。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.getArea());
		
        // 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 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 three 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 when its life has ended.您还将了解对象生命结束后,系统如何清理对象。


Previous page: Passing Information to a Method or a Constructor
Next page: Creating Objects