------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
前几天的学习中,对this关键字的学习是我印象最深刻的。this的用法比较多。在这里整理几点比较常用的。
第一点. this表示前对象自己。
当在一个类中要明确指出使用对象自己的的变量或函数时应该加上this引用。举例说明如下:
publicclass lianxi{
String s = "hello";
public lianxi(String s){
System.out.println("s = " + s);
System.out.println("1: this.s = " + this.s);
this.s = s;
System.out.println("2: this.s = " + this.s);
}
public static void main(String[] args) {
lianxi x = new lianxi("Hello Word!");
}
}
运行结果:
s = Hello World!
1: this.s = Hello
2:this.s = Hello World!
在这个例子中,构造函数Hello中,参数s与类lianxi的变量s同名,这时如果直接对s进行操作则是对参数s进行操作。若要对类lianxi的成员变量s进行操作就应该用this进行引用。运行结果的第一行就
是构造函数中传递过来的参数s值即
Hello World!
; 第二行是对成员变量s的打印;第三行是首先对成员变量s赋值即是传过来的参数s值,然后再打印,所以结果是HelloWorld!
第二点. 把this作为参数传递
当你要把自己作为参数传递给别的对象时,也可以用this。如:
public static void main(String [] args){
A duixang1 = new A();
duixang1.print();
B duixiang2 = new B();
duixiang2.print();
}
}
class A {
public A() {
new B(this).print();
}
public void print() {
System.out.println("Hello from A!");
}
}
class B {
B (){
}
A a;
public B(A a) {
this.a = a;
}
public void print() {
a.print();
System.out.println("Hello from B!");
}
}
运行结果:
Hello from A!
Hello from B!
在这个例子中,对象A的构造函数中,用new B(this)把对象A自己作为参数传递给了对象B的构造函数。
第三点.在构造函数中,通过this可以调用同一class中别的构造函数,如
public class Flower{
Flower (int petals){}
Flower(String ss){}
Flower(int petals, Sting ss){
//petals++;调用另一个构造函数的语句必须在最起始的位置
this(petals);
//this(ss);会产生错误,因为在一个构造函数中只能调用一个构造函数
}
同时应该注意几点问题:
1:在构造调用另一个构造函数,调用动作必须置于最起始的位置。2:不能在构造函数以外的任何函数内调用构造函数。3:在一个构造函数内只能调用一个构造函数。
------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------