Java中的this到底有哪些作用

this的三种用法

1.表示对当前对象的引用
一般应用场景为有参构造和Setter/Getter方法中,也就是我们常说的标准类

public class Person {
	private String name;
	private int age;
	public Person(){
	
	}
	public Person(String name,int age){
		this.name=name;
		this.age=age;
	}
	public String getName() {
	return name;
	}
	public void setName(String name) {
	this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

那么其中的this关键字是指什么勒?
其实就是我们通过Person类生成的对象,比如我们

	Person one=new Person();
	one.setAge(18);

new了一个one对象,通过one对象去调用setAge方法,那么this.age=age就等效于one.age=age,也就是说这个this就是我们的one对象,不信的话可以在setAge里面去打印一下this,看看和我们的one对象是不是一个地址。
也就是说this.age=age等效于我们之前在主函数里面用对象调用成员变量,并且赋值。
也就是说,this是指向对象本身的一个指针

2.在构造方法里面中引用满足参数类型的构造器(其实也就是构造方法)

这个作用其实有点鸡肋,我个人觉得做个了解即可
其实翻译成白话就是,在无参构造中可以直接调用有参,在有参构造中可以直接调用无参。
下面来举例,先说无参构造中调用有参

public class Person {
	String name;
	int age;

	public Person(){**//第二步**
	this("大白袜",23);//无参中调用有参构造	
	}
	public Person(String name,int age){**//第三步**
		this.name=name;
		this.age=age;**//第四步**
	}
	public static void main(String[] args){
		Person two=new Person();**//第一步**
		System.out.println(two.age);**//第五步**
	}
}

也就是说,我们在new一个对象的时候,它的代码执行顺序就如图所示。

同理假如在有参构造中,调用无参就该这么写

public class Person {
	String name;
	int age;
	
	public Person(){
	}
	public Person(String name,int age){
		this();//有参中调用无参构造
		this.name=name;
		this.age=age;
	}

必须注意的是:只能引用一个构造方法,且必须位于开始
什么叫位于开始?
就是this();前面没有任何代码,前面就是public 类名()这行代码.
什么叫只能引用一个构造方法?
就是在有参中调用无参了,就不能再在无参中调用有参了,只能引用一个构造方法
而且,这种用法只能用于构造方法中,别的地方不能用

3.调用当前对象中的其它成员方法

public class Person {
	String name;
	int age;
	
	public void eat(){
		this.sleep();//调用对象其它成员方法,这里this也可以省略
		System.out.pintln("吃饭');
	}
	public void sleep(){
		System.out.pintln("睡觉');
	}

	public static void main(String[] args){
		Person three=new Person();
		three.eat();//输出结果为:睡觉
				      			 吃饭
	}
	
}
发布了8 篇原创文章 · 获赞 0 · 访问量 278

猜你喜欢

转载自blog.csdn.net/codeLearner_CXW/article/details/104182286