典型的Java程序会创建许多对象,您知道这些对象通过调用方法进行交互。通过这些对象的交互,程序可以执行各种任务,例如实现GUI,运行动画或通过网络发送和接收信息。对象完成创建工作后,将回收其资源以供其他对象使用。
这是一个名为CreateObjectDemo
的小程序, 它创建三个对象:一个 Point
对象和两个 Rectangle
对象。您将需要所有三个源文件来编译该程序。
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);
}
}
该程序创建,操作和显示有关各种对象的信息。这是输出:
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
后面三个节使用上面的示例来描述程序中对象的生命周期。从那里,您将学习在您自己的程序中,如何编写创建和使用对象的代码。您还将学习对象寿命到期后,系统如何清理。