2022.9.29 静态变量构造方法

package day19;

public class StaticTest01 {
    public static void main(String[] args) {
        Chinese c1 = new Chinese("张三"); //创建对象
        Chinese c2 = new Chinese("李四");
        //使用静态方法 对象调用静态方法 可以 但不推荐
        System.out.println("姓名是"+c1.getClass()+";国家是:"+c1.getCountry());
        System.out.println("姓名是"+c2.getClass()+";国家是:"+c2.getCountry());

        c1.setName("中国"); //c1的静态变量修改 不属于某一个具体的对象
        //c1的国家 修改了会影响 c2; 因为c1修改的是 静态变量 属于类的
        //因为c1利ic2公共静态变量、类变量指向的是同一个地址
        System.out.println("姓名是:" + c1.getName() +";国家是:" + c1.getCountry());
        System.out.println("姓名是:" + c2.getName() + ";国家是:"+ c2.getCountry());


        Chinese.setCountry( "china"); //推荐使用类调用静态方法
        System.out.println("姓名是:" + c1.getName() +";国家是:" + c1.getCountry());
        System.out.println("姓名是:" + c2.getName() + ";国家是:" + c2.getCountry());
    }
}


class Chinese{
    private static String country ="中华人民共和国"; //静态变量 类变量

    private  String name; //实际变量

    public Chinese(String name){ //构造方法
        //this是对象 谁调用我 谁就是this
        super();
        this.name = name;
    }
    public static void setCountry(String country){
        //类,静态变量 = 局部变量; 这样就可以把两者区分开
        Chinese.country = country;
    }
    public  static String getCountry(){
        return country;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值