静态变量

什么是静态变量?
有statlc的变量叫做静态变量
静态变量在类加载时初始化,不需要new对象,静态变量的空间就开出来了。静态变量存储在方法区

什么时候变量声明为实例的,什么时侯声明为静态的?
如果这个类型的所有对象的某个展性值都是一样的。不建议定义为实例变量。费内存空间,建议定义为类级别特征,定义为静态变量,在方法区中只保留一份。节省内存开销

静态变量会发生空指针现象吗?
静态的都是类相关的,访问时用类名.方法名的方式访问,不需要new对象,即没有空指针异常的发生

public class Student {
  int id;
  String name;
  static String country="Chinese";

  public Student(){
  }
  public Student(int a,String b){
      id =a;
      name=b;
  }
}
public class StudentText {
    public static void main(String args[]) {
        System.out.println(Student.country);
        Student st=new Student(1234,"张三");
        System.out.println(st.name);
        System.out.println(st.id);
        Student st1=new Student(5678,"李四");
        System.out.println(st1.name);
        System.out.println(st1.id);
    }

}


Chinese
张三
1234
李四
5678

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值