Classes and Objects 类和对象
Classes > Declaring Classes
- However, note that the private modifier can only be applied to Nested Classes.
Classes > Providing Constructors for Your Classes
-
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.
-
You can use access modifiers in a constructor's declaration to control which other classes can call the constructor.
Note: If another class cannot call a MyClass constructor, it cannot directly create MyClass objects.
Classes > Passing Information to a Method or a Constructor
-
Arbitrary Number of Arguments 任意数量的参数
-
Follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name.
-
The code in the method body will treat the parameter as an array.
-
-
Passing Reference Data Type Arguments 传递引用数据类型参数
- Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method if they have the proper access level.
More on Classes > Returning a Value from a Method
-
You can override a method and define it to return a subclass of the original method. This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.
-
Note: You can also use interface names as return types. In this case, the object returned must implement the specified interface.
More on Classes > Using the this Keyword
- If present, the invocation of another constructor must be the first line in the constructor.
More on Classes > Controlling Access to Members of a Class
-
At the top level—public or package-private (no explicit modifier).
-
At the member level—public, private, protected, or package-private (no explicit modifier).
-
Access Levels
Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N
More on Classes > Initializing Fields
-
Static Initialization Blocks 静态初始化块
static { // whatever code is needed for initialization goes here }There is an alternative to static blocks — you can write a private static method:
class Whatever { public static varType myVar = initializeClassVariable(); private static varType initializeClassVariable() { // initialization code goes here } } -
Initializing Instance Members 初始化实例成员
-
Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.
-
Initializer blocks for instance variables look just like static initializer blocks but without the static keyword. The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
-
This is especially useful if subclasses might want to reuse the initialization method. The method is final because calling non-final methods during instance initialization can cause problems.
class Whatever { private varType myVar = initializeInstanceVariable(); protected final varType initializeInstanceVariable() { // initialization code goes here } }
-
Nested Classes
-
The Java programming language allows you to define a class within another class.
-
Java 编程语言允许您在另一个类中定义一个类。这样的类称为嵌套类
Terminology: Nested classes are divided into two categories: non-static and static. Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes.
术语: 嵌套类分为两类:非静态和静态。非静态嵌套类称为内部类。声明为静态的嵌套类称为静态嵌套类。
class OuterClass { ... class InnerClass { ... } static class StaticNestedClass { ... } }A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.)
嵌套类是其封闭类的成员。非静态嵌套类(内部类)可以访问封闭类的其他成员,即使它们被声明为私有。静态嵌套类无权访问封闭类的其他成员。作为 OuterClass 的成员,嵌套类可以被声明为 private、public、protected 或 package private。(回想一下,外部类只能被声明为 public 或 package private。)
-
Inner Classes
Like instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to the methods and fields of that object. Additionally, because an inner class is associated with an instance, it cannot define any static members itself.
To instantiate an inner class, you must first instantiate the outer class. Then, use the following syntax to create an inner object within the outer object:
OuterClass outerObject = new OuterClass(); OuterClass.InnerClass innerObject = outerObject.new InnerClass();There are two special kinds of inner classes: local classes and anonymous classes.
有两种特殊的内部类:本地类和匿名类。
-
Static Nested Classes
Like class methods and variables, a static nested class is associated with its outer class. And, just like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class—it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Static nested classes are accessed using the same instantiation syntax as top-level classes:
StaticNestedClass staticNestedObject = new StaticNestedClass();Can only declare its static nested class within the enclosing class?
Serialization?
Serialization of inner classes, including local and anonymous classes, is strongly discouraged. When the Java compiler compiles certain constructs, such as inner classes, it creates synthetic constructs; these are classes, methods, fields, and other constructs that do not have a corresponding construct in the source code. Synthetic constructs enable Java compilers to implement new Java language features without changes to the JVM. However, synthetic constructs can vary among different Java compiler implementations, which means that .class files can vary among different implementations as well. Consequently, you may have compatibility issues if you serialize an inner class and then deserialize it with a different JRE implementation. See the section Implicit and Synthetic Parameters in the section Obtaining Names of Method Parameters for more information about the synthetic constructs generated when an inner class is compiled.
-
Nested Classes > Local Classes
-
Accessing Members of an Enclosing Class
A local class has access to the members of its enclosing class.
本地类可以访问其封闭类的成员。
In addition, a local class has access to local variables. However, a local class can only access local variables that are declared final. When a local class accesses a local variable or parameter of the enclosing block, it captures that variable or parameter. For example, the PhoneNumber constructor can access the local variable numberLength because it is declared final; numberLength is a captured variable.
此外,局部类可以访问局部变量。但是,局部类只能访问声明为 final 的局部变量。当局部类访问封闭块的局部变量或参数时,它会捕获该变量或参数。例如,PhoneNumber 构造函数可以访问局部变量 numberLength,因为它被声明为 final;numberLength 是一个捕获的变量。
However, starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.
但是,从 Java SE 8 开始,本地类可以访问封闭块的本地变量和参数,它们是 final 或实际上是 final。一个变量或参数,其值在初始化后永远不会改变,它实际上是最终的。
-
Local Classes Are Similar To Inner Classes
Local classes declared in a static method can only refer to static members of the enclosing class.
Local classes are non-static because they have access to instance members of the enclosing block. Therefore, they cannot contain most kinds of static declarations.
You cannot declare an interface inside a block; interfaces are inherently static.
You cannot declare static initializers or member interfaces in a local class.
Local classes can have static members provided that they are constant variables.