Home > 类库下载 > java类库 > java-nested classes

java-nested classes

高洛峰
Release: 2016-11-05 16:31:23
Original
2489 people have browsed it

Java allows one class to be defined within another class, which is called class nesting. There are two types of class nesting, static ones are called static nested classes, and non-static ones are called inner classes.

Reason for using nested classes:

Be able to combine classes that are only used in one place in a reasonable way. One class may only be useful for another class. In this case, combining the former with the latter can make the package more concise.

Enhance encapsulation. If there are two classes A and B, class B needs to use a member of class A, and this member happens to be visible only within the class. If B is defined as a nested class of A, then B can use any member of A. , and B can also be declared externally invisible.

Can make the code more readable and maintainable. Nested class code is closer to where it is used than top-level classes, making it easier to view.

Nested classes are also members of a class, so you can also use the visible scope control modifier of class members. Inner classes can use other class members of the class where they are located, while static nested classes cannot use other class members of the class where they are located. class members.

Static Nested Class

Similar to static methods and static fields, static nested classes are related to the class in which they are located. Static nested classes cannot directly use instance variables or instance fields, but can only be referenced through an object. Static nested classes can be regarded as the same as other top-level classes, but they are embedded in other classes to facilitate packaging.

The use of static nested classes is similar to other class members in the class. Here is a demonstration of how to create a static nested class object:

//StaticNestedClass为OuterClass的一个嵌套类OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Copy after login

Inner class (non-static nested class)

An inner class is an instance of the class in which it is located. Related: You can directly use the methods and fields of instance objects. Internal classes are related to instances, so internal classes cannot define static members.

If you need to create an inner class object, you first need to create an object of the class where the inner class is located, as shown below:

//1创建内部类所在类的对象OuterClass outerObject=new OuterClass();//2创建内部类对象
//注意与静态嵌套类的构造器使用方法的差异OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Copy after login

Shading of nested classes

When we declare a type, if its name is the same as the current code block ( For example, a declaration of another type within the same code block (such as inside a class) contains the same name. This phenomenon is called masking. When we need to use the shaded type, we cannot directly reference its name, as shown in the following example:

public class ShadowTest {

    public int x = 0;
//嵌套类
    class FirstLevel {
//以下声明会遮蔽其所在类的名称为x的字段
        public int x = 1;
//以下方法的声明会遮蔽其所在类的名称为x的字段
        void methodInFirstLevel(int x) {
            System.out.println("x = " + x);
            System.out.println("this.x = " + this.x);
            System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);//注意this关键词的使用方法
        }
    }

    public static void main(String... args) {
        ShadowTest st = new ShadowTest();
        ShadowTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel(23);
    }
}
Copy after login

The output of the above code is:

x = 23
this.x = 1
ShadowTest.this.x = 0

Serialization, the tutorial strongly recommends not to serialize inner classes, leaving questions here.

In addition to non-static nested classes, there are also two types of inner classes, one is local class and the other is anonymous class.

Partial classes

Partial classes can be defined in any code block (within curly braces) and are generally used in methods.

Local classes can use class members of the top-level class in which they are located. In addition, local classes can also use local variables. However, the local classes they use must be modified with the final keyword, that is, immutable variables. In Java SE8, local classes can use essentially unchanged local variables, that is, even if the local variable is not modified with the final keyword, its value has never changed since it was initialized.

Starting from java8, local classes can also use parameters of their methods.

Similar to inner classes, local classes cannot define static members, and local classes defined in static methods cannot use instance members.

Interfaces cannot be defined in code blocks because interfaces are static in nature. Excuse members cannot be defined in local classes, but constant variables can be defined in local classes (modified with final, the type is a basic data type or string, and initialized at compile time).

Anonymous classes

Anonymous classes can make the code more concise. It does not need a name and can be declared and instantiated in one step.

The declaration of an anonymous class is an expression, just like calling a constructor, except that it is followed by a code block that defines the class.

The expression of the definition of an anonymous class contains the following parts:

new keyword

An excuse that the anonymous class needs to implement or the name of the inherited parent class

A pair of parentheses, including parameters, to implement an When interface, leave the parameter part blank

Anonymous class body, similar to the body of the class, you can define methods

Anonymous classes have the same types that can be used as local classes:

You can use the class members of the class in which they are located

You can use Local variables with the final modifier in the code block where they are located, or local variables that are no longer assigned after initialization (java8)

For obscured types, they cannot be directly referenced by name

Similarly, anonymous classes cannot declare static members or interfaces. However, constant variables can be declared, and in the class body of an anonymous class, instance fields, instance methods, instance initialization code blocks, and local classes can be declared.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template