标签:amp print 使用 类构造 normal 实例 静态代码块 csu []
前言:本文解决的问题
构造器是用来实例化一个对象,当我们使用new关键字来新建对象时,构造器就会被调用。如果class中含有静态代码块(static)和普通代码块(在{}括号下),新建对象时的调用顺序是:静态代码块>{里面的代码}>构造器。
//父类
public class StaticExample{
{
System.out.println("***This is normal block***");
}
static {
System.out.println("This is first static block");
}
public StaticExample(){
System.out.println("This is constructor");
}
public static String staticString = "Static Variable";
static {
System.out.println("This is second static block and "
+ staticString);
}
static {
staticMethod();
System.out.println("This is third static block");
}
public static void staticMethod() {
System.out.println("This is static method");
}
public static void staticMethod2() {
System.out.println("This is static method2");
}
}
//子类
public class StaticSubClass extends StaticExample{
static {
System.out.println("This is the subclass static block");
}
{
System.out.println("***This is the initialise block in subcluss***");
}
public StaticSubClass() {
System.out.println("This is the subclass constructor");
}
//测试
public static void main(String[] args){
StaticSubClass statEx = new StaticSubClass();
StaticExample.staticMethod2();
}
}
This is first static block
This is second static block and Static Variable
This is static method
This is third static block
This is the subclass static block
This is initialise block base
This is base constructor
This is the initialise block in subcluss
This is the subclass constructor
This is static method2
先分别执行基类的两个静态代码块,然后执行父类的静态代码块,由于父类静态代码块中含有静态方法,因此执行staticMethod(),然后再执行子类的静态代码块,输出为:
This is first static block
This is second static block and Static Variable
This is static method
This is third static block
This is the subclass static block
执行完初static代码块后,再执行父类初始化代码块,然后执行父类的构造器,输出为:
This is initialise block base
This is base constructor
输出为:
This is the initialise block in subcluss
This is the subclass constructor
最后调用继承父类的方法staticMethod2(),输出:
This is static method2
使用new关键字新建对象时,
标签:amp print 使用 类构造 normal 实例 静态代码块 csu []
原文地址:https://www.cnblogs.com/java-learner/p/9559206.html