关于类变量、实例变量之间的区别.md

在写项目的时候突然想用类成员变量用来存数一些配置信息,恍惚脑袋短路,突然发现在这里有一些疑惑测试一下并记下来。

  • 上代码

public class TestClass { private int a= 5;//实例变量
private static int b = 6; //类变量
private static final int c = 6; //常量

public static void main(String[] args) {
    // TODO Auto-generated method stub
    TestClass testA = new TestClass();
    //testA.a = 10;
    testA.b = 20;
    System.out.println(    "testA内部的      a = " + testA.a 
            + "      b = " + testA.b 
            + "      c = " + testA.c);
    
    TestClass testB = new TestClass();
    testB.a = 15;
    testB.b = 30;
    System.out.println(    "testB内部的      a = " + testB.a 
            + "     b = " + testB.b 
            + "      c = " + testB.c);

    TestClass testC = new TestClass();
    System.out.println(    "testC内部的      a = " + testC.a 
            + "      b = " + testC.b 
            + "      c = " + testC.c);        
 }

}

- console结果
 >testA内部的      a = 5     b = 20      c = 6      
 testB内部的      a = 15     b = 30      c = 6     
 testC内部的      a = 5      b = 30      c = 6
- 结论

 **  在 声明类里面方法外的成员变量的中前面的修饰词 `static final` 会有不同的结果**  
- **没有修词的**  是实例化后的对象变量(实例变量)不会影响其他该类实例化的对象
- **static**   会升级成为类变量, 所有由该类实例化的对象都会受到影响
- **static final**  会变成类常量,定义初始化后,无法修改
      
 

转载于:https://my.oschina.net/Wallen/blog/818406

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值