java learning Day10--static keyword

Static keyword

Static

Keywords: Words that are given special meanings by the language are all lowercase when used

static is used to modify the attributes, methods, code blocks and inner classes of the class

After static modifies the member variable, the member variable becomes a static variable

public class Pig {
    
    
    String name;
    /**
     * variety是Pig类共有的都是猪
     * 使用static修饰后变成类变量,类变量只有一份,所有static修饰的变量也只有一份
     */
    static String variety="猪";

    //成员方法中可以访问成员变量,还可以访问静态变量
    public void PigTest(){
    
    
        System.out.println(name);
        System.out.println(variety);
    }

    public static void PigStatic(){
    
    
        //System.out.println(name);
        /*
        静态类的方法只能访问静态成员变量,不能使用非静态成员变量
        静态方法是类的,优先于对象加载
         */
        System.out.println(variety);
    }
}
public class PigTest {
    
    
    public static void main(String[] args) {
    
    

        Pig z= new Pig();
        z.name="猪猪";
        System.out.println(z.variety);


        Pig.variety ="狗";//静态的变量在内存中只有一份,建议使用类名调用
        System.out.println(Pig.variety);//静态方法 通过类名调用

        Pig x= new Pig();
        x.name="狗狗";
        System.out.println(x.variety);
    }

operation result:

猪
狗
狗

There is only one copy of static modification in memory

After being modified, it will be loaded with the loading of the class, prior to the existence of the object

Will be shared by all

public class selltick {
    
    

    static int tick = 11;//票数只有一份,使用static修饰

    public static void SellTick(){
    
    
        tick-=1;
        System.out.println(tick);
    }

    public static void main(String[] args) {
    
    
        selltick.SellTick();
        selltick.SellTick();
    }
}

operation result:

10
9

Code block

The code block is defined in the class, similar to a method without a name

package com.ff.javaopp.day02;

public class Demo {
    
    

    static int num;
      /*
      实例块:与成员方法类似   属于对象的
      每次在创建对象时调用  先于构造方法执行
     */
    {
    
    
        System.out.println("实例块1");
    }
    {
    
    
        System.out.println("实例块2");
    }

    /*
      静态块:属于类
      类加载时执行,只加载一次,多个静态块按顺序执行
     */
    static {
    
    
        System.out.println("静态块1");
    }

    static {
    
    
        System.out.println("静态块2");
    }

    public static void main(String[] args) {
    
    
        System.out.println(Demo.num);
        new Demo();
    }
}

operation result:

静态块1
静态块2
0
实例块1
实例块2

Guess you like

Origin blog.csdn.net/XiaoFanMi/article/details/110233433