对象

原文: https://docs.oracle.com/javase/tutorial/java/javaOO/objects.html

典型的 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

以下三节使用上面的示例来描述程序中对象的生命周期。通过它们,您将学习如何编写在您自己的程序中创建和使用对象的代码。您还将了解系统在生命结束后如何清理系统。