由您决定是否使用super()或this(),因为如果我们不使用this()或super(),则默认情况下编译器会将super()用作构造函数中的第一条语句。
// Java program to illustrate super() by default
// executed by compiler if not provided explicitly
class Parent {
Parent()
{
System.out.println("Parent class's No " +
"argument constructor");
}
Parent(int a)
{
System.out.println("Parent class's 1 argument" +
" constructor");
}
}
class Base extends Parent {
Base()
{
// By default compiler put super()
// here and not super(int)
System.out.println("Base class's No " +
"argument constructor");
}
public static void main(String[] args)
{
new Base();
System.out.println("Inside Main");
}
}
Output:
Parent class's No argument constructor
Base class's No argument constructor
Inside Main
程序流程:
在main内部,我们有新的Base(),然后流程转到Base类的No参数构造函数。
之后,如果我们既不放置super()也不放置this(),则默认情况下编译器放置super()。
因此,流程转到Parent类的No arg构造函数而不是1个参数构造函数。
之后,它会显示父类的No参数构造函数。
之后,当Parent()构造函数完成时,流程又回到基类的No参数构造函数,并执行下一个SOP语句,即Base类的No参数构造函数。
完成此操作后,无参数构造器流程将再次返回main()并在main()内部打印其余语句,即在内部main
但是,如果明确指定,则可以在超级之前使用this()。
// Java program to illustrate super() put by
// compiler always if not provided explicitly
class Parent {
Parent()
{
System.out.println("Parent class's No " +
"argument constructor");
}
Parent(int a)
{
System.out.println("Parent class's one " +
" argument constructor");
}
}
class Base extends Parent {
Base()
{
this(10);
System.out.println("No arg const");
}
Base(int a)
{
this(10, 20);
System.out.println("1 arg const");
}
Base(int k, int m)
{
// See here by default compiler put super();
System.out.println("2 arg const");
}
public static void main(String[] args)
{
new Base();
System.out.println("Inside Main");
}
}
输出:
Parent class's No argument constructor
2 arg const
1 arg const
No arg const
Inside Main