栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/489566.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号