欢迎光临
我们一直在努力

java中,this用途总结。。。-JSP教程,Java技巧及代码

建站超值云服务器,限时71元/月

注:参考了jit(java in thinking),示例都是那里面的。

1、在一个类中,this可以表示该类的当前实例;例如:

public class leaf {

private int i = 0;

leaf increment() {

i++;

return this;

}

void print() {

system.out.println("i = " + i);

}

public static void main(string[] args) {

leaf x = new leaf();

x.increment().increment().increment().print();

}

} ///:~

2、若为一个类写了多个构造器,那么经常都需要在一个构造器里调用另一个构造器,以避免写重复的代码。这时可以使用this,例如:

//: flower.java

// calling constructors with "this"

public class flower {

private int petalcount = 0;

private string s = new string("null");

flower(int petals) {

petalcount = petals;

system.out.println(

"constructor w/ int arg only, petalcount= "

+ petalcount);

}

flower(string ss) {

system.out.println(

"constructor w/ string arg only, s=" + ss);

s = ss;

}

flower(string s, int petals) {

this(petals);

//! this(s); // cant call two!

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

system.out.println("string & int args");

}

flower() {

this("hi", 47);

system.out.println(

"default constructor (no args)");

}

void print() {

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

system.out.println(

"petalcount = " + petalcount + " s = "+ s);

}

public static void main(string[] args) {

flower x = new flower();

x.print();

}

} ///:~

而需要注意的是:在一个类a的内部类b中使用this它表示的并非是a.b的当前实例,而是a的当前实例;

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » java中,this用途总结。。。-JSP教程,Java技巧及代码
分享到: 更多 (0)

相关推荐

  • 暂无文章