JavaSE - static, inner classes

ced485cbb11e458d81a746890b32cf3f.gif

Author: Rukawa Maple Knock Code

Blog Homepage: Rukawa Kaede's Blog

Column: Learn java with me

Quote: Stay hungry stay foolish

If you want to do good things, you must first sharpen your tools. Let me introduce you to a super powerful tool for winning offers from big manufacturers - Niuke.com

Click to register for free and brush the questions with me  

Article directory

1. static modifier member variable

2. static modified member method

3. Static member variable initialization

4. Inner class

instance inner class

static inner class

local inner class


1. static modifier member variable

In Java, members modified by static are called static members or class members. They do not belong to a specific object and are shared by all objects. For example, when we define a student class, we need to express In the classroom where students take classes, the attributes of this classroom do not need to be stored in each student object, but need to be shared by all students. In this case, a static member shared by all objects needs to be defined.

Static modified member variables are called static member variables. The biggest feature of static member variables is that they do not belong to a specific object, but are shared by all objects.

Static member variable features:

1. It does not belong to a specific object, it is an attribute of a class, shared by all objects and not stored in the space of an object

2. It can be accessed either through the object or through the class name, but it is generally recommended to use the class name to access

3. Class variables are stored in the method area

4. The life cycle accompanies the life of the class (ie: created with the loading of the class, destroyed with the unloading of the class)

public class Class {
    private String name;
    private String gender;
    private int age;
    private  static String classRoom = "A123";

    public static void main(String[] args) {
        //静态成员变量可以直接通过类名访问
        System.out.println(Class.classRoom);

        Class c1 = new Class();
        Class c2 = new Class();
        Class c3 = new Class();
        //也可以通过对象访问:但是classRoom是3个对象共享的
        System.out.println(c1.classRoom);
        System.out.println(c2.classRoom);
        System.out.println(c3.classRoom);
    }
}

 Run the above code in debug mode, and then you can see in the monitor window that the static member variables are not stored in a specific object

2. static modified member method

In Java, a member method modified by static is called a static member method , which is a method of a class, not specific to an object. Static members are generally accessed through static methods

public class Class {
    private String name;
    private String gender;
    private int age;
    private  static String classRoom = "A123";
    public static void setClassRoom(String classRoom) {
        Class.classRoom = classRoom;
    }

    public static String getClassRoom() {
        return classRoom;
    }
}

class TestClass{
    public static void main(String[] args) {
        System.out.println(Class.getClassRoom());
    }

}

Output: A123 

Static method features:

1. It does not belong to a specific object, it is a class method

2. It can be called through the object, or through the class name. The static method name (...) method , the latter is more recommended

3. You cannot access any non-static member variables in a static method

Compilation failed: non-static variable this cannot be referenced from static context

'Class.this' cannot be referenced from a static context

 Compilation failed: cannot reference non-static variable age from static context

Non-static field 'age' cannot be referenced from a static context

4. No non-static methods can be called in static methods , because non-static methods have this parameter, and this reference cannot be passed when calling in static methods

 Compilation error: Cannot reference non-static method doClass() from static context

3. Static member variable initialization

Note: Static member variables are generally not initialized in the constructor, and the object-related instance properties are initialized in the constructor.

The initialization of static member variables is divided into two types: in-place initialization and static code block initialization

1. In-place initialization In-place initialization refers to: giving the initial value directly at the time of definition

2. Static code block initialization

A piece of code defined with {} is called a code block

According to the position and keywords defined by the code block, it can be divided into the following four types:

Normal code block: A code block defined in a method.

Building blocks are also called: instance code blocks. Constructor blocks are generally used to initialize instance member variables.

Static Block: A block of code defined using static is called a static code block. Generally used to initialize static member variables.

Synchronized code block

class TestClass{
    public TestClass() {
        System.out.println("不带参数的构造方法");
    }

    public static String classes;
    {

        System.out.println("实例代码块");
    }
    static {
        System.out.println("静态代码块");
    }
    public static void main(String[] args) {
        TestClass testClass = new TestClass();
    }

}

 The static code block is executed first, and the static code block will be executed when the class is loaded, regardless of the code order

 When we execute it again, the static code block will not be executed again, no matter how many objects are generated in the static code block, it will only be executed once

Precautions:

No matter how many objects are generated in a static code block, it will only be executed once

Static member variables are properties of the class , so space is opened up and initialized when the JVM loads the class

If a class contains multiple static code blocks, when compiling the code, the compiler will execute (merge) sequentially according to the defined order.

Instance code blocks are only executed when the object is created

4. Inner class

When there is another part of a thing that needs a complete structure to describe, and this internal complete structure only provides services for external things, then the whole internal complete structure is best to use an inner class. In Java, a class can be defined inside another class or a method, the former is called inner class and the latter is called outer class. Inner classes are also a manifestation of encapsulation

public class OutClass{
    class InnerClass{

    }
}
//OutClass是外部类
//InnerClass是内部类

Precautions:

1. What is defined outside the class class name {} curly brackets, even in a file, cannot be called an inner class

public class A{

}
class B{

}
//A和B是两个独立的类,彼此之前没有关系

2. The inner class and the outer class share the same java source file, but after compilation, the inner class will form a separate bytecode file

public class Test {
    public static void main(String[] args) {
        System.out.println("hello");
    }
    class Test1{
        public void test(){

        }
    }
}

According to the location of the inner class definition, it can generally be divided into the following forms:

1. Member inner class (ordinary inner class: member inner class not modified by static and static inner class : member inner class modified by static)

2. Local inner classes (not talking about modifiers), anonymous inner classes (introduced when learning interfaces)

public class OutClass{

    //成员位置定义:未被static修饰--->实例内部类

    public class InnerClass1{
}

    //成员位置定义:被static修饰--->静态内部类

    static class InnerClass2{
}
    public void method(){

    //方法中也可以定义内部类--->局部内部类:几乎不用

        classInnerClass5{
        }
    }
}

Note: Inner classes are not actually used very much in daily development. You may encounter more when looking at the code in some libraries. Anonymous inner classes are the most used in daily life.

instance inner class

That is, a member inner class that is not modified by static

Look at four questions:

1. How to get object of instance inner class?

OuterClass.InnerClass innerClass = outerClass.new InnerClass();
public class Test {
    //1:如何获取实例内部类的对象
    OuterClass outerClass = new OuterClass();
    //通过外部类对象的引用来调用内部类,可以把实例内部类当作外部类的一个成员
    OuterClass.InnerClass innerClass = outerClass.new InnerClass();

    //两种写法都可
    OuterClass.InnerClass innerClass2 = new OuterClass().new InnerClass();
}
class OuterClass{

    public int data1;
    int data2;
    public static int data3;
    public void test(){
        System.out.println("OuterClass:test");
    }
    //实例内部类
    class InnerClass{

        public int data4;
        int data5;
        //public static int data6;
        public void func(){
            System.out.println("InnerClass:func");
        }
    }
}

2. Why is there an error?

 There cannot be static member variables in the inner class of the instance. If they must be defined, they must be modified with final

Static is a member of the defined class, it will be executed when the class is loaded, and the inner class needs to be executed through the reference of the object, so there will be an error

 final is a constant, similar to const in C, it cannot be modified after initialization, it has been set after compilation

3. Both the outer class and the inner class have the member data1, which one will be printed when called?

class OuterClass{

    public int data1 = 1;
    int data2 = 2;
    public static int data3 = 3;
    public void test(){
        System.out.println("OuterClass:test");
    }
    //实例内部类
    class InnerClass{

        public int data1 = 4;
        int data5 = 5;
        public static final int data6 = 6;
        public void func(){
            System.out.println("InnerClass:func");

            System.out.println(data1);
            System.out.println(data2);
            System.out.println(data3);
            //System.out.println(data4);
            System.out.println(data5);
            System.out.println(data6);
        }
    }
}

Access is to the members of the inner class itself

4. What if you want to access the same member variable in the outer class in the inner class?

 This is ok, or use the reference of the outer class in the instance inner class:

 Use the reference notation of the outer class in the instance inner class:

System.out.println(OuterClass.this.data1);

Precautions:

1. Any member in the outer class can be directly accessed in the instance inner class method

2. The location of the instance inner class is the same as that of the outer class member, so it is also constrained by access qualifiers such as public and private

3. When accessing members of the same name in the inner class method of an instance, access your own first. If you want to access members of the outer class with the same name, you must: outer class name.this.members with the same name to access

4. The inner class object of the instance must be created under the premise of the outer class object

5. The non-static method of the instance inner class contains a reference to the outer class object

6. In the outer class, you cannot directly access the members in the inner class of the instance. If you want to access, you must first create an object of the inner class

static inner class

An inner member class modified by static is called a static inner class

Look at two questions:

1. How to get static inner class object?

OuterClass2.InnerClass2 innerClass2 = new OuterClass2.InnerClass2();
class OuterClass2{

    public int data1 = 1;
    int data2 = 2;
    public static int data3 = 3;
    public void test(){
        System.out.println("OuterClass:test");
    }
    static class InnerClass2{

        public int data1 = 4;
        int data5 = 5;
        public static int data6 = 6;
        public void func(){
            System.out.println("InnerClass2:func");
        }
    }

    public static void main(String[] args) {
        OuterClass2.InnerClass2 innerClass2 = new OuterClass2.InnerClass2();
    }
}

2. The non-static members of the outer class cannot be accessed in the static inner class. The non-static members of the outer class need a reference to the object of the outer class to be accessed.

If you want to visit:

 Precautions:

1. In a static inner class can only access static members in the outer class

2. When creating a static inner class object, you do not need to create an outer class object first

local inner class

Defined in the method body or {} of the outer class. This kind of inner class can only be used in the place where it is defined, and is generally used very rarely. Here is a brief understanding of the syntax format.

public class Test {
    //局部内部类:定义在方法体内部
    // 不能被public、static等访问限定符修饰
    public void method(){
        class InnerClass{

            public void methodInnerClass(){
                System.out.println("hello");
            }

        }
        //只能在该方法体内部使用,其他位置都不能用
        InnerClass innerClass= new InnerClass();
        innerClass.methodInnerClass();
    }

    public static void main(String[] args) {
        //编译失败
        Test.InnerClassinnerClass=null;
    }
}

Precautions:

1. Local inner classes can only be used inside the defined method body

2. Cannot be modified by modifiers such as public and static

3. The compiler also has its own independent bytecode file, the naming format: external class name $ internal class name.class

 One class corresponds to one bytecode file

4. Rarely use 

 "The sharing of this issue is here, remember to give the blogger a three-link, your support is the biggest driving force for my creation!

ced485cbb11e458d81a746890b32cf3f.gif

 

Guess you like

Origin blog.csdn.net/chenchenchencl/article/details/126179618