【问题标题】:Behavior of static blocks with Abstract classes具有抽象类的静态块的行为
【发布时间】:2013-12-30 11:09:37
【问题描述】:

儿童班:

public class ChildExtending extends ParentAbstract{

    public int childInt =111213;
    static{
        System.out.println("child static block executed");
    }

    public ChildExtending() {
        System.out.println("child const initialized");
    }
    public void MethodInChild(){
        System.out.println("MethodInChild called");
    }
    public static void main(String[] args){
        System.out.println(ParentAbstract.parentInt);
        System.out.println(ChildExtending.parentInt);
    }
}

抽象类:

public abstract class ParentAbstract {
    public static int parentInt=80713; 
    static{
        System.out.println("parent static executed");
        parentInt=9;
    }

    public ParentAbstract(){
        System.out.println("parentAbstract initialized");
    }

    public void MethodInParent(){
        System.out.println("MethodInParent called");
    }

}

主类:

public class MainForCheck {
    public static void main(String[] args){
    /*  ParentAbstract pa = new ParentAbstract(){

        };*/

    /*  ChildExtending ce = new ChildExtending();
        ce.childInt=5;*/

        /*ChildExtending ce = new ChildExtending();
        ce.childInt=5;
        ce.MethodInChild();
        System.out.println("pareny int is"+ce.parentInt);*/


        ChildExtending ce = new ChildExtending();
        ce.MethodInParent();

    }
}

这给了我输出:

父静态执行 ]

执行的子静态块

parentAbstract 已初始化

子常量初始化

MethodInParent 调用

为什么不是这样?

父静态执行

parentAbstract 已初始化

执行的子静态块

子常量初始化

MethodInParent 调用

【问题讨论】:

    标签: java abstract-class static-block


    【解决方案1】:

    首先需要初始化ChildExtending(作为一种类型)。这将产生

    的输出
     parent static executed
     child static block executed
    

    根据section 12.4.2 of the JLS

    只有在类型初始化后才能调用构造函数,此时您将获得以下输出:

     parentAbstract initialized
     child const initialized
    

    并且一旦对象被构造出来,就可以在其上调用实例方法,输出如下:

    MethodInParent called
    

    我认为您缺少的部分是类型必须在构造函数启动之前完全初始化。构造函数调用无法初始化只是足够的超类来调用其构造函数,然后初始化子类。除此之外,如果你在超类构造函数中调用getClass(),那必须是一个完全初始化的类——它必须是子类,因为这就是对象的一个实例。

    【讨论】:

      【解决方案2】:

      每当类第一次加载时,它的静态块总是首先执行。所以这里它的父子静态块被执行然后实例块或方法执行

      【讨论】:

        猜你喜欢
        • 2019-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-12
        • 2021-06-28
        • 2011-11-15
        • 1970-01-01
        • 2012-05-28
        相关资源
        最近更新 更多