[Java] Static keyword based on Java

Overview 

        Static stands for static, used to modify members (including member variables and member methods). Define the variables shared by all objects of the current class as static.

interview method

Two access methods:

1) You can use object calls: objects. Static members

2) You can use the class name to call: class name. static member

Recommendation: use class name to call

public  class Person{
    static string country;
}  


public class Test{
    public static void main(String[] args){
        //创建对象
        Person person=new Person();
        person.country;
        //或者直接类名.静态成员
        Person.country;
    }
}

Access rules for static members

Access rules:

1) Static can only directly access static, not non-static

2) Non-static can directly access static and non-static

package com.itheima_01;
public class AAA {
    //静态变量
    static int a ;
    //普通变量
    int b;

    //静态方法
    public static void method1(){
        System.out.println(a);  //静态方法可以访问静态变量
        System.out.println(b);  //静态方法不可以访问非静态变量
        method2();              //静态方法可以访问静态方法
        method3();              //静态方法不可以访问非静态方法
    }

    public static void method2(){
    }

    //普通方法
    public void method3(){
        System.out.println(a);
        System.out.println(b);
        method1();
        method4();
    }

    public void method4(){
    }
}

Notes on static methods

1) Once the static keyword is used, the member variables do not belong to themselves, but belong to the class. As long as they are objects of this class, they all share the same data. For example, the classrooms of peers and students are the same and can be declared as static

2) Whether it is a static variable or a static method, it is recommended to use the class name to call

3) Static methods cannot directly call non-static methods . Reason: In memory, static content is generated before non-static content. That is to say: future generations know the ancestors, but the ancestors do not know the future generations [for example, we know Qin Shihuang, but Qin Shihuang does not know us] ( Static is always preferred to non-static )

4) Static methods do not belong to objects, but belong to classes.

5) This call cannot be used in a static method. This represents the current object, and a static method belongs to a class. After the class is loaded, the object does not necessarily exist. If you use this call, an error will occur .

6) The first execution of the static code block is executed only once

Guess you like

Origin blog.csdn.net/weixin_43267344/article/details/107886087