标签:strong highlight log void png 构造 class 对象 sys
4、指出下面程序的运行结果。
class A {
static {
System.out.print("1");
}
public A() {
System.out.print("2");
}
}
class B extends A{
static {
System.out.print("a");
}
public B() {
System.out.print("b");
}
}
public class Hello {
public static void main(String[] args) {
A ab = new B();
ab = new B();
}
}
答:执行结果:1a2b2b。创建对象时构造器的调用顺序是:先初始化静态成员,然后调用父类构造器,再初始化非静态成员,最后调用自身构造器。
如下demo:
Parent.java
/**
* @author: snowing
* @date : 2017年4月18日
*
*/
public class Parent {
static {
System.out.println("Parent‘s 静态代码块");
}
{
System.out.println("Parent‘s 代码块");
}
public Parent() {
System.out.println("Parent‘s 构造方法");
}
}
Child.java
/**
* @author: snowing
* @date : 2017年4月18日
*
*/
public class Child extends Parent{
static {
System.out.println("Child‘s 静态代码块");
}
{
System.out.println("Child‘s 代码块");
}
public Child() {
System.out.println("Child‘s 构造方法");
}
public static void main(String[] args) {
new Child();
}
}
输出:

java面试基础题------》Java 中的父子类静态代码块,代码块,构造方法执行顺序
标签:strong highlight log void png 构造 class 对象 sys
原文地址:http://www.cnblogs.com/SnowingYXY/p/6727304.html