Java this 那些事儿

本文深入解析Java中的this关键字,阐述其在构造方法、返回当前对象引用及区分成员变量名与参数名方面的重要作用,并通过实例代码进行详细演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本我过去在哪里,自我即应在哪里。---弗洛伊德

总要有个事物来代表类的当前对象,就像C++中的this指针一样,Java中的this关键字就是代表当前对象的引用。

它有三个主要的作用:

1、在构造方法中调用其他构造方法。

      比如有一个Student类,有三个构造函数,某一个构造函数中调用另外构造函数,就要用到this(),而直接使用Student()是不可以的。

2、返回当前对象的引用。

3、区分成员变量名和参数名。

看下面的例子:

public class Student
{
	private String name;
	private int age;
	private String college;
	public Student()
	{
		age = 20;
	}
	public Student(String name)
	{
		this();//can not be call Student,only use this() method.
		this.name = name;
		System.out.println("this student name is "+name);
	}
	public Student(String name,String college)
	{
		this(name);//C++中可以直接用Student(name)调用其他构造函数
		this.college = college;
		System.out.println("this student name is "+name+" college is "+college);		
	}

	public Student upgrade()
	{
		age++;
		return this;
	}

	public void print()
	{
		System.out.println("name is: "+name
				+" age is: "+age
				+" college is: "+college);
	}

	public static void main(String[] args)
	{
		Student student1 = new Student("linc");
		Student student2 = new Student("linc","shenyang college");
		student2.upgrade().print();
	}
}

迷失在茫茫的对象海洋时,不要忘了用this来找到自我。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值