本文介绍了非静态块在静态块之前执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个顶级类(BaseClass和B),BaseClass中有main方法,还有内部类(名为Laptop).我知道每当加载类时都会执行静态块,但是对于以下代码:

I have two top-level classes(BaseClass and B), BaseClass has main method in it and also has inner class(named Laptop). I know that static block is executed whenever class is loaded but for the following code:

           package kkk;

public class BaseClass
{

static BaseClass e=new BaseClass();


public BaseClass()
{
System.out.println("In baseclass constructor");
}

{
System.out.println("in baseclass nonstatic block");
}

static
{
System.out.println("in baseclass static block");
}

protected static class Laptop
{
int x=8;

public Laptop()
{
    System.out.println("Inside laptop class");
}

void m1()
{
    System.out.println("Inside inner class method");
}
}



public void hem()
{
System.out.println("In base class hem");
}



public static void main(String args[])
{

e.hem();
System.out.println("In main method baseclass");
B h=new B();
h.bhel();
}
}

B类{无效bhel(){BaseClass.Laptop obj =新BaseClass.Laptop();System.out.println(obj.x);obj.m1();}}

通过运行以上代码,我得到的输出为:

By running above code, i am getting output as:

in baseclass nonstatic block
In baseclass constructor
in baseclass static block
In base class hem
In main method baseclass
Inside laptop class
8
Inside inner class

e是静态参考变量,必须为其分配内存.因此,执行了静态块.但是,为什么要在静态块之前执行非静态块呢?

e is static reference variable and memory must be allotted to it. So, static block is executed. But, why non-static block is executed before static block??

推荐答案

所有静态变量声明和静态初始化块都是按照初始化类时在源代码中出现的顺序进行评估/执行的.

All static variable declarations and static initialization blocks are evaluated/executed in the order they appear in the source code when the class is initialized.

static BaseClass e=new BaseClass();

这将在初始化类时创建 BaseClass 的实例,并使实例初始化块在构造函数执行之前被调用.

this creates an instance of BaseClass when the class is initialized and causes the instance initialization block to be called before the constructor is executed.

由于此行出现在静态初始化块之前,因此它在该块之前执行,这意味着实例初始化块在静态初始化块之前被调用.

Since this line appears before the static initialization block, it is executed before that block, which means the instance initialization block is called before the static initialization block.

这篇关于非静态块在静态块之前执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:42