Java中的static详细讲解

【1】static可以修饰:属性,方法,代码块,内部类。

【2】static修饰属性;

public class Test {
    
    
    //属性:
    int id;
    static int sid;
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
    
    
        //创建一个Test类的具体的对象
        Test t1 = new Test();
        t1.id = 10;
        t1.sid = 10;
        Test t2 = new Test();
        t2.id = 20;
        t2.sid = 20;
        Test t3 = new Test();
        t3.id = 30;
        t3.sid = 30;
        //读取属性的值:
        System.out.println(t1.id);
        System.out.println(t2.id);
        System.out.println(t3.id);
        System.out.println(t1.sid);
        System.out.println(t2.sid);
        System.out.println(t3.sid);
    }
}

内存分析:
在这里插入图片描述

一般官方的推荐访问方式:可以通过类名.属性名的方式去访问:

static修饰属性总结:
(1)在类加载的时候一起加载入方法区中的静态域中
(2)先于对象存在
(3)访问方式: 对象名.属性名 类名.属性名(推荐)

static修饰属性的应用场景:某些特定的数据想要在内存中共享,只有一块 --》这个情况下,就可以用static修饰的属性

public class MsbStudent {
    
    
    //属性:
    String name;
    int age;
    static String school;
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
    
    
        MsbStudent.school = "static详细讲解";
        //创建学生对象:
        MsbStudent s1 = new MsbStudent();
        s1.name = "张三";
        s1.age = 19;
        //s1.school = "static详细讲解";
        MsbStudent s2 = new MsbStudent();
        s2.name = "李四";
        s2.age = 21;
        //s2.school = "static详细讲解";
        System.out.println(s2.school);
    }
}

属性:
静态属性 (类变量)
非静态属性(实例变量)

【3】static修饰方法;

public class Demo {
    
    
    int id;
    static int sid;
    public void a(){
    
    
        System.out.println(id);
        System.out.println(sid);
        System.out.println("------a");
    }
    //1.static和public都是修饰符,并列的没有先后顺序,先写谁后写谁都行
    static public void b(){
    
    
        //System.out.println(this.id);//4.在静态方法中不能使用this关键字
        //a();//3.在静态方法中不能访问非静态的方法
        //System.out.println(id);//2.在静态方法中不能访问非静态的属性
        System.out.println(sid);
        System.out.println("------b");
    }
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
    
    
        //5.非静态的方法可以用对象名.方法名去调用
        Demo d = new Demo();
        d.a();
        //6.静态的方法可以用   对象名.方法名去调用  也可以 用  类名.方法名 (推荐)
        Demo.b();
        d.b();
       
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31762741/article/details/109965747