《Java编程思想》学习笔记(四)——this总结

用法一: 引用当前对象的成员变量:如果在类的方法中定义了与类的成员变量同名的局部变量, 则在该方法中,类的成员变量会被覆盖,为了在该方法中引用类的成员变量,则用到了this,例如:
 
   
package com.exercise;

public class Test {

/**
*
@param args
*/
int i = 0 ;

public void print() {
int i = 1 ;
System.out.println(i);
System.out.println(
this .i);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Test test = new Test();
test.print();
}

}
用法二: 将当前对象作为参数传递:有时候,在类的某一个方法中需要调用一个外部方法,该方法的参数是该类的对象,这种情况下,调用时便可将this传递进去。例如:
 
   
class Person {
public void eat(Apple apple) {
Apple peeled
= apple.getPeeled();
System.out.println(
" Yummy " );
}
}

class Peeler {
static Apple peel(Apple apple) {
// ... remove peel
return apple; // Peeled
}
}

class Apple {
Apple getPeeled() {
return Peeler.peel( this );
}
}

public class PassingThis {
public static void main(String[] args) {
new Person().eat( new Apple());
}
}
用法三: 在类的重载构造函数中调用其他构造函数:当一个类有多个构造函数时,为了增加代码的复用,可以在一个构造函数中调用其他构造函数,但,只允许在当前构造函数中的第一句调用一次其他构造函数,否则将无法编译通过,如下面代码所示:
 
   
package com.exercise;

public class Test {

public int i;
Test(
int i) {
this .i = i;
}
Test(String s) {
System.
out .println(s);
}
Test(
int i, String s) {
this (s);
// this(i); 编译无法通过
this .i = i;
}
public static void main(String[] args) {
Test test
= new Test( 6 , " Hello " );
System.
out .println(test.i);
}
}
用法四:在内部类或匿名类中的用法,还未接触,待补充
注意:1、this不能用在static方法里  2、在构造函数中通过this调用其他构造函数的时候只能放在第一句

转载于:https://www.cnblogs.com/Pickuper/archive/2011/06/26/2090246.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值