首页 > 试题广场 >

以下代码的输出内容是什么public class Pa...

[单选题]
以下代码的输出内容是什么
public class Parent {
private static final String PARENT = "parent";
private static final String CHILD = "child";
public Parent() {
System.out.print(PARENT + "A ");
}
static {
System.out.print(PARENT + "B ");
}
{
System.out.print(PARENT + "C ");
}
static class Child extends Parent {
public Child() {
System.out.print(CHILD + "A ");
}
static {
System.out.print(CHILD + "B ");
}
{
System.out.print(CHILD + "C ");
}
}
public static void main(String[] args) {
Child child = new Child();
}
}
  • parentB childB parentC parentA childC childA
  • parentA parentB parentC childA childB childC
  • parentB childB parentA parentC childA childC
  • parentA childA parentB childB parentC childC
执行顺序: 1.静态代码块 2.非静态代码块 3.构造方法
发表于 2021-05-27 07:53:08 回复(0)
静态代码块伴随类加载执行,没名字的代码块(其实应该叫初始化代码块)伴随构造方法的执行,子类的构造方法中会首先执行父类的构造方法
发表于 2021-06-16 17:31:07 回复(0)
public class Parent {
    private static final String PARENT = "parent";
    private static final String CHILD = "child";

    public Parent() {
        System.out.print("parentC ");
        System.out.print("parentA ");
    }

    public static void main(String[] var0) {
        new Parent.Child();
    }

    static {
        System.out.print("parentB ");
    }

    static class Child extends Parent {
        public Child() {
            System.out.print("childC ");
            System.out.print("childA ");
        }

        static {
            System.out.print("childB ");
        }
    }
}
对Parent类编译之后会看到非静态代码块中的代码被加入了构造方法。再根据
父类静态代码块 -> 子类静态代码块 -> 父类构造方法 -> 子构造方法的顺序,可知答案。

如果问
public static void main(String[] args) {
    Child child1 = new Child();
    Child child2 = new Child();
}
的结果,则是
parentB childB parentC parentA childC childA 
parentC parentA childC childA 
以为静态方法指挥执行一次


发表于 2021-10-16 21:39:32 回复(0)