java继承的静态初始化 [英] java static initialization with inheritance

查看:134
本文介绍了java继承的静态初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


    public class Main {

        public static void main(String[] args) {
            System.out.println(B.x);
        }

    }
    class A {
        public static String x = "x";
    }
    class B extends A {
        static {
            System.out.print("Inside B.");
        }
    }

问题:为什么输出为:x。但不是:内部Bx

Question: Why output will be: "x". But not: "Inside B.x"

推荐答案

Bx 问题的引用以下字节码:

The reference to B.x issues the following bytecode:

getstatic       #3   <Field int B.x>

根据 Java虚拟机规范


Java虚拟机说明anewarray,checkcast,getfield,
getstatic ,instanceof,invokedynamic,invokeinterface,invokespecial,
invokestatic,invokevirtual,ldc,ldc_w,multianewarray, new,
putfield和putstatic使符号引用到运行时
常量池。执行任何这些指令需要
其符号引用的分辨率

The Java virtual machine instructions anewarray, checkcast, getfield, getstatic, instanceof, invokedynamic, invokeinterface, invokespecial, invokestatic, invokevirtual, ldc, ldc_w, multianewarray, new, putfield, and putstatic make symbolic references to the runtime constant pool. Execution of any of these instructions requires resolution of its symbolic reference.

所以JVM应该解析符号引用 Bx 。字段解析为指定如下

So the JVM should resolve the symbolic reference to B.x. The field resolution is specified like this:


要解决从D到
类或接口C中的字段的未解析符号引用,字段
引用给出的符号引用必须先解析(§5.4.3.1)。

To resolve an unresolved symbolic reference from D to a field in a class or interface C, the symbolic reference to C given by the field reference must first be resolved (§5.4.3.1).

...

解析字段引用时,字段解析首先尝试
在C及其超类中查找引用字段

When resolving a field reference, field resolution first attempts to look up the referenced field in C and its superclasses:

如果C声明具有
字段引用指定的名称和描述符的字段,则字段查找成功。声明的字段是字段查找的
结果。

If C declares a field with the name and descriptor specified by the field reference, field lookup succeeds. The declared field is the result of the field lookup.

否则,字段查找以递归方式应用于指定类的直接
超接口或接口C。

Otherwise, field lookup is applied recursively to the direct superinterfaces of the specified class or interface C.

否则,如果C具有超类S,则将字段查找以递归方式应用于$ b $。

否则,字段查找失败。

换句话说,JVM将解析 Bx 进入 Ax 。这就是为什么只需要加载 A 类。

In other words the JVM will resolve B.x into A.x. This is why only A class needs to be loaded.

这篇关于java继承的静态初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆