Java 关键字Static 静态变量 静态方法

在这里插入图片描述

被static关键字修饰的方法和变量被称为静态变量和静态方法
静态变量和静态方法是存储在方法区内存中的是在类被加载时就会在方法区内存中为其分配存储空间
静态的东西也被称为类级别的东西可以直接使用类名.变量名或者方法名的形式访问,与对象无关。
不需要创建对象就可以直接引用。
Test 类

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Chinese zhangSan = new Chinese("1","zhangSan","Chinese");
        Chinese liSi = new Chinese("2","liSi","Chinese");
        System.out.println("身份证号为"+zhangSan.id+" 姓名为"+zhangSan.name+" 国际为"+zhangSan.country);
        System.out.println("身份证号为"+liSi.id+" 姓名为"+liSi.name+" 国际为"+liSi.country);
    }
}


Chinese 类

public class Chinese {
    
    
    String id;//身份证号,每个人的身份证号都不同
    String name;//姓名,每个人的名字都不同
    String country;//每个人的国际都相同都是Chinese
//在此处我们将country定义为了实例变量但是当我们每次创建对象时都会为其分配内存空间
//但是不同的内存空间存储的确是一样的值,会造成内存空间的浪费
    public Chinese() {
    
    
    }

    public Chinese(String id, String name, String country) {
    
    
        this.id = id;
        this.name = name;
        this.country = country;
    }

    public String getId() {
    
    
        return id;
    }

    public void setId(String id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getCountry() {
    
    
        return country;
    }

    public void setCountry(String country) {
    
    
        this.country = country;
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
Test 类

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Chinese zhangSan = new Chinese("1","zhangSan");
        Chinese liSi = new Chinese("2","liSi");
        System.out.println("身份证号为"+zhangSan.id+" 姓名为"+zhangSan.name+" 国际为"+Chinese.country);
        System.out.println("身份证号为"+liSi.id+" 姓名为"+liSi.name+" 国际为"+Chinese.country);
    }
}


Chinese 类

public class Chinese {
    
    
    String id;//身份证号,每个人的身份证号都不同
    String name;//姓名,每个人的名字都不同
    static String country="Chinese";//此时的country被我定义为了静态变量静态变量是类级别的变量我们可以
    //采用类名.变量名的方式访问country
    //每个人的国际都相同都是Chinese
//在此处我们将country定义为了实例变量但是当我们每次创建对象时都会为其分配内存空间
//但是不同的内存空间存储的确是一样的值,会造成内存空间的浪费
    public Chinese() {
    
    
    }

    public Chinese(String id, String name) {
    
    
        this.id = id;
        this.name = name;
    }

    public String getId() {
    
    
        return id;
    }

    public void setId(String id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }
}

Guess you like

Origin blog.csdn.net/qq_45858803/article/details/121309121