java 静态 初始化 继承,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.");

}

}

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

解决方案

The reference to B.x issues the following bytecode:

getstatic #3

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.

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

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).

...

When resolving a field reference, field resolution first attempts to

look up the referenced field in C and its superclasses:

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.

Otherwise, field lookup is applied recursively to the direct

superinterfaces of the specified class or interface C.

Otherwise, if C has a superclass S, field lookup is applied

recursively to S.

Otherwise, field lookup fails.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值