The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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.您还将了解对象生命结束后,系统如何清理对象。