Documentation

The Java™ Tutorials
Hide TOC
Summary of Creating and Using Classes and Objects创建和使用类和对象的小结
Trail: Learning the Java Language
Lesson: Classes and Objects
Section: More on Classes

Summary of Creating and Using Classes and Objects创建和使用类和对象的摘要

A class declaration names the class and encloses the class body between braces.类声明命名类并将类主体括在大括号之间。The class name can be preceded by modifiers.类名前面可以有修饰符。The class body contains fields, methods, and constructors for the class.类主体包含类的字段、方法和构造函数。A class uses fields to contain state information and uses methods to implement behavior.类使用字段来包含状态信息,并使用方法来实现行为。Constructors that initialize a new instance of a class use the name of the class and look like methods without a return type.初始化类的新实例的构造函数使用类的名称,看起来像没有返回类型的方法。

You control access to classes and members in the same way: by using an access modifier such as public in their declaration.通过在类和成员的声明中使用访问修饰符(如public)来控制对类和成员的访问。

You specify a class variable or a class method by using the static keyword in the member's declaration.通过在成员声明中使用static关键字来指定类变量或类方法。A member that is not declared as static is implicitly an instance member.未声明为static的成员隐式地是实例成员。Class variables are shared by all instances of a class and can be accessed through the class name as well as an instance reference.类变量由类的所有实例共享,可以通过类名和实例引用进行访问。Instances of a class get their own copy of each instance variable, which must be accessed through an instance reference.类的实例获取每个实例变量各自的副本,必须通过实例引用访问这些副本。

You create an object from a class by using the new operator and a constructor.通过使用new运算符和构造函数从类创建对象。The new operator returns a reference to the object that was created.新操作符返回对已创建对象的引用。You can assign the reference to a variable or use it directly.可以将引用指定给变量,也可以直接使用它。

Instance variables and methods that are accessible to code outside of the class that they are declared in can be referred to by using a qualified name.可以使用限定名引用在声明它们的类之外的代码可以访问的实例变量和方法。The qualified name of an instance variable looks like this:实例变量的限定名称如下所示:

objectReference.variableName

The qualified name of a method looks like this:方法的限定名称如下所示:

objectReference.methodName(argumentList)

or:或:

objectReference.methodName()

The garbage collector automatically cleans up unused objects.垃圾收集器会自动清理未使用的对象。An object is unused if the program holds no more references to it.如果程序不再持有对某个对象的引用,则该对象未被使用。You can explicitly drop a reference by setting the variable holding the reference to null.通过将保存引用的变量设置为null,可以显式删除引用。


Previous page: Initializing Fields
Next page: Questions and Exercises: Classes