final,static,this,super

Final, static, this, super keyword summary

final keyword

The final keyword is mainly used in three places: variables, methods, and classes.

  1. For a final variable, if it is a variable of basic data type, its value cannot be changed once it is initialized; if it is a variable of reference type, it cannot be made to point to another object after its initialization.

  2. When a class is modified with final, it indicates that the class cannot be inherited. All member methods in the final class will be implicitly designated as final methods.

  3. There are two reasons for using the final method. The first reason is to lock the method to prevent any inherited classes from modifying its meaning; the second reason is efficiency. In the early Java implementation version, final methods will be converted to inline calls. But if the method is too large, you may not see any performance improvement brought by the inline call (the current Java version no longer needs to use the final method for these optimizations). All private methods in the class are implicitly designated as final.

static keyword

The static keyword mainly has the following four usage scenarios:

  1. Modified member variables and member methods: The members modified by static belong to the class, not to an object of a single class, and are shared by all objects in the class, and it is possible and recommended to call through the class name. The member variables declared by static are static member variables, and the static variables are stored in the method area of ​​the Java memory area. Call format:类名.静态变量名 类名.静态方法名()
  2. Static code block: The static code block is defined outside the method in the class, and the static code block is executed before the non-static code block (static code block—>non-static code block—>construction method). No matter how many objects are created in this class, the static code block is executed only once.
  3. Static inner classes (if static modified classes can only modify inner classes): There is one biggest difference between static inner classes and non-static inner classes: non-static inner classes will implicitly save a reference after compilation is completed. It refers to the outer class that created it, but the static inner class does not. The absence of this reference means: 1. Its creation does not need to rely on the creation of peripheral classes. 2. It cannot use any non-static member variables and methods of the outer class.
  4. Static guide package (used to import static resources in the class, new features after 1.5): The format is: import staticthese two keywords can be used together to specify the import of a specified static resource in a class, and there is no need to use the class name to call the class For static members, you can directly use static member variables and member methods in the class.

this keyword

The this keyword is used to refer to the current instance of the class. E.g:

class Manager {
    
    
    Employees[] employees;
     
    void manageEmployees() {
    
    
        int totalEmp = this.employees.length;
        System.out.println("Total employees: " + totalEmp);
        this.report();
    }
     
    void report() {
    
     }
}

In the above example, the this keyword is used in two places:

  • this.employees.length: Access the variables of the current instance of the class Manager.
  • this.report(): Call the method of the current instance of the class Manager.

This keyword is optional, which means if the example above behaves the same without using this keyword. However, using this keyword may make the code more readable or understandable.

super keyword

The super keyword is used to access the variables and methods of the parent class from the subclass. E.g:

public class Super {
    
    
    protected int number;
     
    protected showNumber() {
    
    
        System.out.println("number = " + number);
    }
}
 
public class Sub extends Super {
    
    
    void bar() {
    
    
        super.number = 10;
        super.showNumber();
    }
}

In the example above, Sub class to access the parent class member variable number and call its parent class's Super showNumber()methods.

Points to note when using this and super:

  • In the constructor super()when other constructors call the parent class, the statement must be the first line of the constructor, otherwise the compiler will complain. In addition, when this calls other construction methods in this class, it should also be placed in the first line.
  • This and super cannot be used in static methods.

Explain briefly:

The members modified by static belong to the class, not to an object of a single class, and are shared by all objects in the class. And this represents the reference to the object of this class, pointing to the object of this class; and super represents the reference to the parent object, pointing to the parent object; therefore, this and super are things in the category of objects, and static methods are things in the category of classes. .

reference

  • https://www.codejava.net/java-core/the-java-language/java-keywords
  • https://blog.csdn.net/u013393958/article/details/79881037

Detailed explanation of static keyword

The static keyword mainly has the following four usage scenarios

  1. Modify member variables and member methods
  2. Static code block
  3. Modified class (only inner class can be modified)
  4. Static guide package (used to import static resources in the class, new features after 1.5)

Modify member variables and member methods (commonly used)

The members modified by static belong to the class, not to a certain object of a single class, and are shared by all objects in the class, and it is possible and recommended to call through the class name. The member variables declared by static are static member variables, and the static variables are stored in the method area of ​​the Java memory area.

The method area, like the Java heap, is a memory area shared by each thread. It is used to store data such as class information, constants, static variables, and code compiled by the just-in-time compiler that have been loaded by the virtual machine. Although the Java virtual machine specification describes the method area as a logical part of the heap, it has an alias called Non-Heap (non-heap), and the purpose should be to distinguish it from the Java heap.

The method area in the HotSpot virtual machine is also often referred to as the "permanent generation", and in essence the two are not equivalent. It is only because the HotSpot virtual machine design team uses the permanent generation to implement the method area, so that the garbage collector of the HotSpot virtual machine can manage this part of the memory like the Java heap. But this is not a good idea, because it is easier to encounter memory overflow problems.

Call format:

  • 类名.静态变量名
  • 类名.静态方法名()

If the variable or method is private, it means that the property or method can only be accessed inside the class but not outside the class.

testing method:

public class StaticBean {
    
    

    String name;
    //静态变量
    static int age;

    public StaticBean(String name) {
    
    
        this.name = name;
    }
    //静态方法
    static void SayHello() {
    
    
        System.out.println("Hello i am java");
    }
    @Override
    public String toString() {
    
    
        return StaticBean{
    
     +
                name=' + name + ''' + age + age +
                '}';
    }
}
public class StaticDemo {
    
    

    public static void main(String[] args) {
    
    
        StaticBean staticBean = new StaticBean(1);
        StaticBean staticBean2 = new StaticBean(2);
        StaticBean staticBean3 = new StaticBean(3);
        StaticBean staticBean4 = new StaticBean(4);
        StaticBean.age = 33;
        StaticBean{
    
    name='1'age33} StaticBean{
    
    name='2'age33} StaticBean{
    
    name='3'age33} StaticBean{
    
    name='4'age33}
        System.out.println(staticBean+ +staticBean2+ +staticBean3+ +staticBean4);
        StaticBean.SayHello();Hello i am java
    }

}

Static code block

The static code block is defined outside the method in the class, and the static code block is executed before the non-static code block (static code block-non-static code block-construction method). No matter how many objects are created in this class, the static code block is executed only once.

The format of the static code block is

static {    
语句体;   
}

There can be multiple static code blocks in a class, and the location can be placed at will. It is not in any method body. The JVM will execute these static code blocks when loading the class. If there are multiple static code blocks, the JVM will follow them in the class Execute them in the order in which they appear, and each code block will only be executed once.

The static code block can assign values ​​to the static variables defined after it, but cannot access it.

Static inner class

There is one biggest difference between a static inner class and a non-static inner class. We know that a non-static inner class will implicitly save a reference after the compilation is complete. The reference refers to the outer class that created it, but the static inner class No. The absence of this reference means:

  1. Its creation does not need to rely on the creation of peripheral classes.
  2. It cannot use any non-static member variables and methods of the outer class.

Example (Static inner class implements singleton mode)

public class Singleton {
    
    
    
    //声明为 private 避免调用默认构造方法创建对象
    private Singleton() {
    
    
    }
    
   // 声明为 private 表明静态内部该类只能在该 Singleton 类中被访问
    private static class SingletonHolder {
    
    
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getUniqueInstance() {
    
    
        return SingletonHolder.INSTANCE;
    }
}

When the Singleton class is loaded, the static inner class SingletonHolder is not loaded into memory. Only when you call getUniqueInstance()a method to trigger SingletonHolder.INSTANCEwhen SingletonHolder will be loaded at this time initialization INSTANCE instance, and to ensure INSTANCE JVM is instantiated only once.

This method not only has the benefit of lazy initialization, but also supports thread safety provided by the JVM.

Static guide package

The format is: import static

These two keywords can be used together to specify to import the specified static resources in a certain class, and you do not need to use the class name to call the static members in the class, you can directly use the static member variables and member methods in the class



 //将Math中的所有静态资源导入,这时候可以直接使用里面的静态方法,而不用通过类名进行调用
 //如果只想导入单一某个静态方法,只需要将换成对应的方法名即可
 
import static java.lang.Math.;//换成import static java.lang.Math.max;具有一样的效果
 
public class Demo {
    
    
  public static void main(String[] args) {
    
    
 
    int max = max(1,2);
    System.out.println(max);
  }
}

to add on

Static and non-static methods

Static methods belong to the class itself, and non-static methods belong to every object generated from the class. If the operation performed by your method does not depend on the various variables and methods of its class, set it to static (this will make the program's footprint smaller). Otherwise, it should be non-static.

Example

class Foo {
    
    
    int i;
    public Foo(int i) {
    
     
       this.i = i;
    }

    public static String method1() {
    
    
       return An example string that doesn't depend on i (an instance variable);
       
    }

    public int method2() {
    
    
       return this.i + 1;  Depends on i
    }

}

You can call a static method like this: Foo.method1(). If you try to call method2 in this way, it will fail. But this works:Foo bar = new Foo(1);bar.method2();

to sum up:

  • When calling a static method externally, you can use the "class name. method name" method or the "object name. method name" method. The instance method has only the latter way. In other words, you can call a static method without creating an object.
  • When a static method accesses the members of this class, only static members (that is, static member variables and static methods) are allowed to access, but not instance member variables and instance methods; there is no such restriction for instance methods

static{}Static code block and {}non-static code block (constructed code block)

Similarities: All are executed when the JVM loads the class and before the execution of the construction method. Multiple definitions can be defined in the class. When multiple definitions are defined, they are executed in the defined order. Generally, some static variables are assigned in the code block.

Differences: The static code block is executed before the non-static code block (static code block-non-static code block-construction method). The static code block is executed only once for the first time new and will not be executed afterwards, while the non-static code block is executed once every new time. Non-static code blocks can be defined in ordinary methods (but have little effect); static code blocks cannot.

Fix issue #677 : Static code blocks may be executed at the first new, but not necessarily only at the first new. For example, by Class.forName("ClassDemo")also executed when creating Class object.

Under normal circumstances, if some code, such as some of the most commonly used variables or objects in the project, must be executed when the project is started, static code blocks are required. This kind of code is actively executed. If we want to design that we can call methods in the class without creating objects, such as: Arrays, Character, String, etc., we need to use static methods. The difference between the two is that static code blocks are automatically executed while static methods It is executed when it is called.

Example:

public class Test {
    
    
    public Test() {
    
    
        System.out.print("默认构造方法!--");
    }

    //非静态代码块
    {
    
    
        System.out.print("非静态代码块!--");
    }

    //静态代码块
    static {
    
    
        System.out.print("静态代码块!--");
    }

    private static void test() {
    
    
        System.out.print("静态方法中的内容! --");
        {
    
    
            System.out.print("静态方法中的代码块!--");
        }

    }

    public static void main(String[] args) {
    
    
        Test test = new Test();
        Test.test();//静态代码块!--静态方法中的内容! --静态方法中的代码块!--
    }
}

The output of the above code:

静态代码块!--非静态代码块!--默认构造方法!--静态方法中的内容! --静态方法中的代码块!--

When performing only the Test.test();output:

静态代码块!--静态方法中的内容! --静态方法中的代码块!--

When performing only the Test test = new Test();output:

静态代码块!--非静态代码块!--默认构造方法!--

The difference between a non-static code block and a constructor is: A non-static code block is to initialize all objects uniformly, while the constructor is to initialize the corresponding object, because there can be multiple constructors, which constructor will create something. Such objects, but no matter which object is created, the same construction code block will be executed first. In other words, what is defined in the construction code block is the initialization content common to different objects.

reference

  • httpsblog.csdn.netchen13579867831articledetails78995480
  • httpwww.cnblogs.comchenssyp3388487.html
  • httpwww.cnblogs.comQian123p5713440.html
    );` when output:
静态代码块!--非静态代码块!--默认构造方法!--

The difference between a non-static code block and a constructor is: A non-static code block is to initialize all objects uniformly, while the constructor is to initialize the corresponding object, because there can be multiple constructors, which constructor will create something. Such objects, but no matter which object is created, the same construction code block will be executed first. In other words, what is defined in the construction code block is the initialization content common to different objects.

reference

:

  • httpsblog.csdn.netchen13579867831articledetails78995480
  • httpwww.cnblogs.comchenssyp3388487.html
  • httpwww.cnblogs.comQian123p5713440.html

Guess you like

Origin blog.csdn.net/qq_38893133/article/details/108071063