典型的Java程序会创建许多对象,如您所知,通过调用方法进行交互。通过这些对象交互,程序可以执行各种任务,例如实现GUI,运行动画,或通过网络发送和接收信息。一旦一个对象完成了创建它的工作,它的资源将被再循环供其他对象使用。
这是一个名为CreateObjectDemo的小程序,它创建三个对象:一个Point对象和两个Rectangle对象。您将需要所有三个源文件来编译此程序。
source code for Point:
public class Point{ private int x; private int y; public int GetX(){ return x; } public int GetY(){ return y; } public void SetX(int x){ this.x = x; } public void SetY(int y){ this.y = y; } public Point(int x,int y){ this.x = x; this.y = y; } }Source Code For Rectangle:
public class Rectangle{ private int width = 0; public int GetWidth(){ return width; } public void SetWidth(int width){ this.width = width; } private int height = 0; public int GetHeight(){ return height; } public void SetHeight(int height){ this.height = height; } public Point origin; public Rectangle(){ origin = new Point(0,0); } public Rectangle(int width,int height){ SetWidth(width); SetHeight(height); } public Rectangle(Point origin,int width,int height){ this.origin = origin; SetWidth(width); SetHeight(height); } public int getArea(){ return width * height; } public void move(int x, int y ){ this.origin.SetX(x); this.origin.SetY(y); } }Source Code For CreateObjectDemo:
public class CreateObjectDemo{ public static void main(String[] args){ Point originOne = new Point(23,94); Rectangle rectOne = new Rectangle(originOne,100,200); Rectangle rectTwo = new Rectangle(50,100); System.out.println("Width of rectOne: " + rectOne.GetWidth()); System.out.println("Height of rectOne: " + rectOne.GetHeight()); System.out.println("Area of rectOne: " + rectOne.getArea()); rectTwo.origin = originOne; System.out.println("x Position of rectTwo: " + rectTwo.origin.GetX()); System.out.println("y Position of rectTwo: " + rectTwo.origin.GetY()); rectTwo.move(40,72); System.out.println("x Position of rectTwo: " + rectTwo.origin.GetX()); System.out.println("y Position of rectTwo: " + rectTwo.origin.GetY()); } }这个程序的输出结果为:
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接下来的文章,我们将使用上述示例来描述程序中对象的生命周期。从他们,您将学习如何编写在自己的程序中创建和使用对象的代码。您还将了解一个对象在生命结束后如何清理系统。
