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修饰的变量

猜你喜欢

转载自www.cnblogs.com/9coding/p/11945045.html