this 关键字的使用

this 的基本使用

如果你希望在方法的内部获得对当前对象的引用,那么就可以使用 this 关键字,this 只能在方法的内部使用,表示对 “调用方法的那个对象” 的引用。

public int weight;
public int num;

public void test(){
int total = this.weight * this.num;
}

但是如果在一个方法内部调用当前类的另一个方法,那么就不必使用 this,直接调用即可。

public class Tank {

	public int weight;
	
	public void info (){
	    System.out.println("weight: " + weight);
	}
	
	public void test(){
	    info();
	}
}

不要在每一个方法和字段前面引用 this 关键字,如果 this 用在了没必要的地方,会让看代码的人不知所措。好钢用在刀刃上,在必要的时候再使用 this,有助于形成简洁直观的代码风格。

返回当前对象的引用

当需要返回当前对象的引用的时候,可以直接使用 this 关键字来返回,如下:

public class Apple {

	int num = 0;
	
	public Apple increament() {
	    num ++;
	    //返回当前引用
	    return this;
	}
	
	public static void main(String[] args) {
	    Apple a = new Apple();
	    int result = a.increament().increament().num;
	    System.out.println(result);
	}
}

this 返回了当前对象的引用,所以可以在一条语句里面对同一个对象多次执行多次操作。

将当前对象传递给其他方法

如果当前类需要调用外部方法,而且必须要将自身传递给外部方法,那么就必须要使用 this 关键字。

public class Apple {

	Apple getPeeled(){
	    //this 将当前对象传递给其他方法调用
	    return Peeler.peel(this);
	}
	
	public static void main(String[] args) {
	    Apple a = new Apple();
	    a.getPeeled();
	}
	}
	
	class Peeler {
	public static Apple peel(Apple apple) {
	return apple;
	}
}

在构造器中调用构造器

通常,使用 this 来表示对当前对象的引用,有时候,一个类中有多个构造器,其中可能想在一个构造器中调用另一个构造器,这个时候也可以使用 this 来实现。

public class People {

	private String name;
	private int age;
	
	public People() {
	}
	
	public People(String name) {
	    super();
	    this.name = name;
	}
	
	public People(String name, int age) {
	    //使用 this 来调用另一个构造器
	    this(name);
	    //不能使用 this 调用两个构造器
	    //this();
	    //由于局部变量和全局变量同名,那么使用 this 可以避免歧义
	    this.age = age;
	}
	
	public void info (){
	    //不能在普通方法中使用 this 来调用构造器
	    //this();
	    System.out.println("the name of the people is : " +  name);
	}
}

上述代码表明,可以在一个构造器中使用 this 调用另一个构造器,但不能调用两个,而且必须将构造器的调用置于方法的起始处,同时不能在普通方法中使用 this 来调用构造器,否则编译器报错。

还有一点,就是局部变量和全局变量同名的时候,使用 this 可以避免产生歧义,this 后面紧跟的变量代表全局变量。

static 和 this

我们知道可以在没有创建任何对象的前提下,通过类本身来调用 static 方法,也正是因为这种调用不是通过向对象发送消息完成的,所以在 static 方法中不存在 this。这也就是常说的 static 方法就是没有 this 的方法,在 static 方法中不能调用非静态方法,反过来是可以的。

欢迎关注公众号:一盐难进

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值