Java面试 - static 修饰的变量和方法有哪些特点?

1、static修饰的变量和方法,在类加载时即被初始化,可直接通过类名.变量名和类型.方法名进行调用。
2、static修饰的变量,在类加载时会被分配到数据区的方法区。类的实例可共享方法区中的变量。如果static修饰的变量发生改变,那么所有类实例引用的变量都会一起发生改变。
3、static修饰的方法中不能使用this或super,static修饰的方法属于类的方法,而this或super只是对象的方法。
4、static修饰的方法不能引用非static 修饰的变量, 在类加载过程中,当static修饰的方法加载完成时,非static修饰的变量还未加载,所以无法引用非static修饰的变量。
5、非static修饰的方法可以引用static 修饰的变量,在类加载过程中,static修饰的变量优先完成加载,所以当非static修饰的方法完成加载后可以引用static 修饰的变量。

举例

假设Student 类有static 修饰的变量name和方法getName(String name), 那么是否可以直接通过类名调用呢?

public class Student {
  private static String name;
  private static void getName(){
    System.out.println(name);
  }
  public static void main(String[] args) {
    Student.name = "Jack Ma";
    Student.getName();
  }
}

运行结果:

Jack Ma

可见,static 修饰的变量和方法是可以直接通过类名调用的。
那么,在static 修饰的main方法内, Student 对象s1 和s2 是否可以直接调用static 修饰的变量和方法呢?

public class Student {
  private static String name;
  public static void getName(){
    System.out.println(name);
  }
  public static void main(String[] args) {
    Student s1 = new Student();
    s1.name = "大黄";
    s1.getName();
    Student s2 = new Student();
    s2.name = "二黄";
    s2.getName();
  }
}

运行结果:

大黄
二黄

从运行结果来看,在static 修饰的main方法内,Student 对象s1 和s2 是可以直接调用static 修饰的变量和方法。
如果此时修改static 修饰的变量name方法,那么Student对象s1, s2调用的变量name是否也会一起被修改呢?

public class Student {
  private static String name;
  public static void getName(){
    System.out.println(name);
  }
  public static void main(String[] args) {
    Student s1 = new Student();
    // 修改static 修饰的变量name
    s1.name = "Jack";
    s1.getName();
    Student s2 = new Student();
    s2.getName();
  }
}

运行结果:

Jack
Jack

从运行结果来看,当对象s1修改了在方法区(数据共享区)的static变量name,那么对象s2调用的static变量name必然会一起被修改。
在static修饰的方法中是否可以应用this呢?
在static修饰的方法中不能应用this.png
在static修饰的方法中是否可以应用super呢?
在static修饰的方法中不能应用super.png
在static修饰的方法是否能引用非static 修饰的变量呢?
static修饰的方法不能引用非static 修饰的变量.png
非static修饰的方法是否能引用static修饰的变量呢?

public class Student {
  private static String name;
  private int age;
  public void getInfo(){
    // 非static 方法getInfo()引用static修饰的变量name
    System.out.println("姓名:"+ name + ", 年龄" + age);
  }
  public static void main(String[] args) {
    Student s1 = new Student();
    //通过类名Student直接调用static 变量 name
    Student.name = "Jack Ma";
    s1.age = 19;
    s1.getInfo();
  }
}

运行一下

姓名:Jack Ma, 年龄19

可见,非static修饰的方法可以引用static修饰的变量。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值