class Bike7{
int speed;
Bike7(){
System.out.println("speed is "+speed);
}
{
speed=100;
}
public static void main(String args[]){
Bike7 b1=new Bike7();
Bike7 b2=new Bike7();
}
}
Output:speed is 100 speed is 100
方法
构造函数
程序块
class Bike8{
int speed;
Bike8(){
System.out.println("constructor is invoked");
}
{
System.out.println("instance initializer block invoked");
}
public static void main(String args[]){
Bike8 b1=new Bike8();
Bike8 b2=new Bike8();
}
}
instance initializer block invoked constructor is invoked instance initializer block invoked constructor is invoked
创建类的实例时,将创建实例初始化程序块。
实例构造器块在父类构造函数被调用之后(即在super()构造函数调用之后)被调用。
实例初始化程序块按它们出现的顺序排列。
class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B2 extends A{
B2(){
super();
System.out.println("child class constructor invoked");
}
{
System.out.println("instance initializer block is invoked");
}
public static void main(String args[]){
B2 b=new B2();
}
}
Output:parent class constructor invoked instance initializer block is invoked child class constructor invoked
class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B3 extends A{
B3(){
super();
System.out.println("child class constructor invoked");
}
B3(int a){
super();
System.out.println("child class constructor invoked "+a);
}
{
System.out.println("instance initializer block is invoked");
}
public static void main(String args[]){
B3 b1=new B3();
B3 b2=new B3(10);
}
}
parent class constructor invoked instance initializer block is invoked child class constructor invoked parent class constructor invoked instance initializer block is invoked child class constructor invoked 10