黑马程序员-关于this的一些感悟

 

------- <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 class Lianxi1 {


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>、期待与您交流! ----------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值