java调用构造函数的作用_this 关键字的功用-显示调用构造函数。

Calling constructors from constructors

sited by p118When you write several constructors for a class, there are times when you’d like to call one

constructor from another to avoid duplicating code.

当你为一个类写了好几个构造函数,有时候你需要在一个构造函数中去调用另外一个构造函数来避免重复写代码。

You can make such a call by using the thiskeyword.

这个时候你可以通过调用THIS关键字来完成。

Normally, when you say this, it is in the sense of “this object” or “the current object,” and by

itself it produces the reference to the current object.

在通常的情况下,你说this 的时候,它都被用来表示当前的对象,产生一个对象的引用。

In a constructor, the thiskeyword takes on a different meaning when you give it an argument list.

可是在构造函数里面,当你给它一些形参的时候this 关键字却可以表示另外一种含义。

It makes an explicit call to the constructor that matches that argument list.

那就是你它可以显示的调用一个和它的形参数目一样的构造方法。

Thus you have a straightforward way to call other constructors。

因此你就可以轻松自如的调用其它的构造方法。

//: initialization/Flower.java

// Calling constructors with "this"

import static net.mindview.util.Print.*;

public class Flower {

int petalCount = 0;

String s = "initial value";

Flower(int petals) {

petalCount = petals;

print("Constructor w/ int arg only, petalCount= "

+ petalCount);

}

Flower(String ss) {

print("Constructor w/ String arg only, s = " + ss);

s = ss;

}

Flower(String s, int petals) {

this(petals);

//! this(s); // Can’t call two!

this.s = s; // Another use of "this"

print("String & int args");

}

Flower() {

this("hi", 47);

print("default constructor (no args)");

}

void printPetalCount() {

//! this(11); // Not inside non-constructor!

print("petalCount = " + petalCount + " s = "+ s);

}

public static void main(String[] args) {

Flower x = new Flower();

x.printPetalCount();

}

} /* Output:

Constructor w/ int arg only, petalCount= 47

String & int args

default constructor (no args)

petalCount = 47 s = hi

*///:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值