转载自:Java this指针的使用_胜利Fred的博客-CSDN博客
定义
指当前正在访问的这段代码的对象。this只能在类中的非静态方法中使用,静态方法和静态代码块中不能出现this。
作用
当我们在一个类中写一个方法时,当传入的参数的参数名与该类的成员变量名相同,并且把参数赋值给与之同名的成员变量时,此时编译器并不知道到底是参数赋值给成员变量,还是成员变量赋值给参数;所以就有了this指针的诞生。当我们把this指针加上后,就是把传进来的参数赋值给变量。
实例
在方法中调用成员变量
public class StringBuffer_1 {
private String name;
private int age;
private String sex;
StringBuffer_1(String name, int age, String sex) {
setName(name);
setAge(age);
setSex(sex);
printinfo();
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(String sex) {
this.sex = sex;
}
public void printinfo() {
System.out.println("name:" + name + "\n" + "age:" + age + "\n" + "sex:" + sex);
}
public static void main(String[] args) {
StringBuffer_1 stringBuffer_1 = new StringBuffer_1("kwy", 21, "女");
}
}
将当前对象传递给其他方法
class Person{
public void eat(Apple apple){
Apple peeled=apple.getPeeled();
System.out.println("nihao");
}
}
class Peeled{
static Apple peel(Apple apple){
return apple;
}
}
class Apple{
Apple getPeeled(){
return Peeled.peel(this);
}
}
public class StringBuffer_1 {
public static void main(String[] args) {
new Person().eat(new Apple());
}
}
在构造器中调用构造器
public class StringBuffer_1 {
int petalCount=0;
String s ="initial value";
StringBuffer_1(int petals){
petalCount=petals;
System.out.println("Constructor w/int arg only,petalCount ="+petalCount);
}
StringBuffer_1(String ss){
System.out.println("Constructor w/ String arg only,s ="+ss);
s=ss;
}
StringBuffer_1(String s,int petals){
this(petals);//可以用this调用一个构造器,但却不能调用两个,必须将构造器调用置于最起始处,否则会编译出错。
this.s=s;
petalCount=petals;
System.out.println("Strng & int args");
}
StringBuffer_1(){
this("hi",34);
System.out.println("default constructor (no args)");
}
void printPetalCount(){
System.out.println("petalcount="+petalCount+"s="+s);
}
public static void main(String[] args) {
StringBuffer_1 si=new StringBuffer_1();
si.printPetalCount();
}
}