Java 请解释一下这个输出是如何产生的? 输出
已调用车辆构造函数Java 请解释一下这个输出是如何产生的? 输出,java,Java,已调用车辆构造函数 已调用匿名块 调用Car构造函数在本例中,首先调用超类构造函数,Vehicle。 然后,匿名块被执行,它是一组命令,被“附加”在所有构造函数的开头。最后执行Car中的实际构造函数。如果您查看编译器将此代码转换为什么,希望这是显而易见的: class Vehicle{ Vehicle(){ System.out.println("Vehicle Constructor Invoked"); } } public class Car extends Vehicl
已调用匿名块
调用Car构造函数在本例中,首先调用超类构造函数,
Vehicle
。
然后,匿名块被执行,它是一组命令,被“附加”在所有构造函数的开头。最后执行
Car
中的实际构造函数。如果您查看编译器将此代码转换为什么,希望这是显而易见的:
class Vehicle{
Vehicle(){
System.out.println("Vehicle Constructor Invoked");
}
}
public class Car extends Vehicle{
Car(){
System.out.println("Car Constructor Invoked");
}
{
System.out.println("Anonymous Block Invoked");
}
public static void main(String args[]){
Car c=new Car();
}
}
如果您使用
javap
对代码进行反编译,您可以看到这一点。这是什么让您感到困惑?请阅读本文
class Vehicle{
Vehicle(){
super();
System.out.println("Vehicle Constructor Invoked");
}
}
public class Car extends Vehicle{
Car(){
// First the super constructor is invoked. If you don't invoke it explicitly, the compiler adds the call.
super();
// Then, instance initializers are inlined into any constructor invoking `super`, after the super.
System.out.println("Anonymous Block Invoked");
// Then, the rest of the constructor body.
System.out.println("Car Constructor Invoked");
}
public static void main(String args[]){
Car c=new Car();
}
}