Java foundation of the final, static keyword

I. Introduction

  About two keywords should be in the development of the more common use of the frequency is relatively high. Interfaces, constants, static method and so on. However, this does not mean the frequent use must be able to clearly understand understanding, one can say Zichou to play Mao. Now, these two common uses keywords to do summary record, after the assault to facilitate review and knowledge.

Second, the keyword final

  final, literally as "final", generally designated "immutable" in Java. Class can be used to modify, process, process parameters, and variables.

  1, modified class

   In the final modified class, on behalf of the class can not be inherited. This means that if a class is determined not inherited use, it can be designed as a final type. A typical example is the String class.

  2, modification methods

  The final modification methods can be inherited, but can not be rewritten. It can be overloaded.

  3, parameter modification methods

  final modification method when the parameter represented by the internal execution method, it is possible not to change the value of a parameter. But if the object is referenced, the attribute values ​​can be changed application object.

  4, modifying variables

  In the modified final variables are immutable representatives, that is often said that the "constant." final modifications at the time, to allow an assignment, after the life cycle of the class, you can not modify it.

  In both cases there is modifying variables: basic types of data and object data. When the modified basic types of data, values ​​are immutable. In the modified object data that references to objects it is immutable, but can be modified attribute values ​​inside the object.

  final modified variables must be initialized before use, one way is to give the default value at the time of declaration. Another is to set via the constructor.

  5, sample code

com.cfang Package; 

Import the java.util.Calendar; 

Import lombok.Data; 
Import Lombok. extern .slf4j.Slf4j; 

@ SLF4J 
public  class T3 { 
    

    public  static  void main (String [] args) {
         // - modified variable 
        final int B = 0 ;
         / * * 
         * compiler error: local variable B of The Final CAN BE Not Assigned It MUST BE blank and the using Not Assignment Compound A. 
         * / 
//         B = 2; 
        
        // - modifying method parameters 
        DemoCls CLS = new new DemoCls (); 
        cls.setAge (10);
        log.info("democls age : {}", cls.getAge());
        int a = 10;
        sayHello(a, cls);
        log.info("after call sayHello, democls age : {}", cls.getAge());
    }
    
    private static void sayHello(final int a, final DemoCls cls) {
        /**
         *     编译报错:The final local variable a cannot be assigned. It must be blank and not using a compound assignment
         */
//        a = 11;
//        cls = new DemoCls();
        
        cls.setAge ( . 11 ); 
    } 
} 

@Data 
class DemoCls {
     Private  int Age; 
} 

// - method of modifying 
@ SLF4J
 class the Person {
     public Final void saySth () { 
        log.info ( " I AM Person " ); 
    } 
} 

SLF4J @ 
class Male the extends the Person {
     / * * 
     * compile error: not the override of can at the Final method, from the Person 
     * modified method can not be overridden 
     * / 
//     public void saySth Final () {
 //        log.info("i am male");
//    }
    
    public final void saySth(String msg) {
        log.info("i am male");
    }
}

  Wherein the parameter modification methods, if a reference object, the object can be changed attribute values, it is well understood: a reference variable cls, final modified reference variable, but this reference variable cls defining a reference can not be changed, the actual the value of the referenced object itself can be modified. Text language organization may not be very clear, as shown below, at a glance to know the meaning of the said to be expressed.

  

Third, the keyword static

  static, static. In Java, it can be used to modify the generally static variables, methods and code blocks.

  1, modifying variables

  modified static variables, known as static variables. static variables are shared by all class objects, only one copy in memory, with the initialization of the class is loaded. The corresponding non-static variable, each instance of an object belongs to itself, the presence of multiple memory parts, do not affect each other.

  2, modification methods

  static modification of the method, called static method. Call the static method does not rely on instance of an object can be accessed, therefore, is not a static method of this. Because of this feature, and non-static method invocation depends on instance objects, it is not a static method can be used without non-static member properties and methods. In contrast, the non-static method can be directly accessed using static member variables and methods. Similarly, the static method is not super. Can be summarized under the phrase: irrelevant since the static objects and specific examples, while this, super closely related objects and specific examples, therefore, static and this, super potential, such as fire, as day and night.

  3, the modified code blocks

  modified static block, when loading the class initialization will be performed in the order of loading static blocks, and the life cycle, loaded only once. Based on this characteristic, can be designed to optimize the performance of a program, only some of the one-time initialization loaded content, static blocks may be placed.

  4, sample code

com.cfang Package; 

Import Lombok. extern .slf4j.Slf4j; 

@ SLF4J 
public  class T4 { 
    
    Private  static  int A;
     Private  static  int B;
     Private  static  int C; 
    
    static { 
        log.info ( " the init value A " ); 
        A = 10 ; 
    } 
    
    { 
        / * * 
         * Common code blocks, depending on the object instance 
         * / 
        log.info ( " the init value C " ); 
        C= 12 is ; 
    } 

    public  static  void main (String [] args) {
         // - a static non-static method call 
        / * * 
         * not directly accessible 
         * / 
//         sayHello1 (); 
        new new T4 () sayHello1 ();. 
        
        // - static method directly call 
        the sayHello (); 
        
        // - static block of code initializes resources 
        log.info ( " value A: {} " , A); 
        log.info ( " value B: {} " , B); 
        log .info ( " value C: {} " , C); 
    } 
    
    Private  static void the sayHello () { 
        log.info ( " say Hello " ); 
    } 
    
    Private  void sayHello1 () { 
        log.info ( " say hello1 " );
         // - non-static method called directly 
        the sayHello (); 
    } 
    
    static { 
        log. info ( " the init value B " ); 
        B = . 11 ; 
    } 
}

  5, static Common Mistakes

package com.cfang;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class T5 {
    
    private static int a = 10;

    public static void main(String[] args) {
        new T5().printVal();
        
        //-- The field DemoCls01.b is not visible
        DemoCls01.b;
    }
    
    private void printVal() {
        int a = 11;
        log.info("value a : {}", this.a);
    }
}

@Data
class DemoCls01{
    private static int b;
}

  5.1、static 的 this

  In the above code, the final run printVal method, the result is output: value a: 10. In fact, this is well understood: the current object this refers to, but by the new T5 () printVal () call, then, this refers to the instance of the object generation is the current newly created, static modification of the variable itself is all class objects. shared, and a method printVal local variables belong, with this instance of the object and is not associated. Therefore, the output is 10.

  5.2, static and visibility

  Visibility does not change the static variable or method. The above code, main process, DemoCls01.b will compile error.

  5.3, static and local variables

  Java specification, clearly stated: static keyword can not modify local variables.

IV Summary

  final and static, once used in combination to represent modified values ​​of attributes, it can not be modified, and may be accessed via the class name; modification methods, indicating that the method can not be overridden, can be called without new object.

  Suddenly thought, interfaces interface, the default modifier for the member variables public static final, the default method modifiers public abstract.

Guess you like

Origin www.cnblogs.com/eric-fang/p/11593570.html