java this() super(),Java super()和this()的区别用法及代码示例

由您决定是否使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值