java - Java中的静态变量

标签 java inheritance static-members

class Parent
{
  public static String sName = "Parent";
  static
  {
    System.out.println("Parents static block called");      
    sName = "Parent";
  }
}

class Child extends Parent
{
  public static String sName1;
  static
  {
    System.out.println("Childs static block called");       
    sName = "Child";
    sName1 = "Child";
  }
}

public class Inheritance
{
  public static void main(String []args)
  {     
    System.out.println(Child.sName);
    System.out.println(Parent.sName);
  }
}

在上面的代码片段中,我有一个 ' Parent '类和a'Child ' 扩展 Parent 的类。我了解静态变量在之间共享的事实 父类及其所有子类。当我运行上面的程序时,输出是

Parents static block called
Parent
Parent

我想知道为什么即使执行了 ' System.out.println(Child.sName); 后 Child 的静态 block 也没有执行'。我不知道为什么只有父类被加载而不是 Childs 类。现在当我修改main()时如下所示的函数加载了 Child 的类。

public static void main(String []args)
{       
  System.out.println(Child.sName);
  System.out.println(Parent.sName);
  System.out.println(Child.sName1);   //sName is declared in Child class.
  System.out.println(Parent.sName);
}

现在的输出如下所示,符合预期。现在必须加载 Child 类,因为我们正在引用在 Child 类中声明的静态变量 sName1。

Parents static block called
Parent
Parent
Childs static block called
Child
Child

静态变量'sName '现在有'Child ' 作为它的值。我的问题是,为什么在修改之前在主函数的第一行本身中进行引用后,为什么 Child 类没有被加载?

请指教。

最佳答案

来自JLS

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.

在第一种情况(第一组打印语句)中,您只能访问 sName 变量,并且它属于 Parent 类,因此子类是未初始化。

在第二组打印语句中,您访问了sName1变量,该变量属于Child类,因此此时Child类已初始化。

没关系,即使你访问了Child.sName,它实际上引用了Parent.sName,所以它不会加载子级

关于java - Java中的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21821865/

相关文章:

java - 选中或未选中时立即获取复选框状态

java - JPanel 背景颜色在某些边框类型上溢出到边框之外

inheritance - Dojo 小部件声明字符串 - 它是临时的吗?

java - 快速JAVA继承问题

c++ - 哪个目标文件包含以下静态模板化 "member variable"?

java - 使用 ThermometerPlot 类时,如何看到 Mercurial 的转变?

java - 当我运行作业时,springBatch 中的 ItemReadListener 未运行

java - 我无法执行虚拟方法调用

c# - C# 中静态成员的别名?

c++ - 由于 header 中的特化初始化而避免重复符号?