典型的Java程序会创建许多对象,您知道这些对象通过调用方法进行交互。通过这些对象的交互,程序可以执行各种任务,例如实现GUI,运行动画或通过网络发送和接收信息。对象完成创建工作后,将回收其资源以供其他对象使用。
    这是一个名为CreateObjectDemo的小程序, 它创建三个对象:一个 Point对象和两个 Rectangle对象。您将需要所有三个源文件来编译该程序。

    1. public class CreateObjectDemo {
    2. public static void main(String[] args) {
    3. // Declare and create a point object and two rectangle objects.
    4. Point originOne = new Point(23, 94);
    5. Rectangle rectOne = new Rectangle(originOne, 100, 200);
    6. Rectangle rectTwo = new Rectangle(50, 100);
    7. // display rectOne's width, height, and area
    8. System.out.println("Width of rectOne: " + rectOne.width);
    9. System.out.println("Height of rectOne: " + rectOne.height);
    10. System.out.println("Area of rectOne: " + rectOne.getArea());
    11. // set rectTwo's position
    12. rectTwo.origin = originOne;
    13. // display rectTwo's position
    14. System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
    15. System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);
    16. // move rectTwo and display its new position
    17. rectTwo.move(40, 72);
    18. System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
    19. System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);
    20. }
    21. }

    该程序创建,操作和显示有关各种对象的信息。这是输出:

    1. Width of rectOne: 100
    2. Height of rectOne: 200
    3. Area of rectOne: 20000
    4. X Position of rectTwo: 23
    5. Y Position of rectTwo: 94
    6. X Position of rectTwo: 40
    7. Y Position of rectTwo: 72

    后面三个节使用上面的示例来描述程序中对象的生命周期。从那里,您将学习在您自己的程序中,如何编写创建和使用对象的代码。您还将学习对象寿命到期后,系统如何清理。