this关键字

this代表对当前对象的一个引用,用于调用属性,方法,及本类中构造方法。具体如下

1.在方法中用this调用成员变量,解决与局部变量的重名问题

this在实例方法中通常被省略,除非实例方法中包含与成员变量同名的局部变量时,访问成员变量需要使用this。

public class Student{
	
	String name="Tom" ;
	
		public Student(String name ) {
			System.out.println(name+"在说话");
			System.out.println(this.name+"在学习");
		}	
		public static void main(String[] args) {
			Student stu = new Student("Jim");
		}
}

运行结果

Jim在说话
Tom在学习(可见this可用来代表成员变量)

2.用this调用成员方法

public class Student {
	private String name;
	public void doHomework(){
		System.out.println(this);//谁调用此方法,this代表谁
		System.out.println(this.name+"正在做作业......");
	}
	public static void main(String[] args) {
		Student stu = new Student();//将地址赋值给stu
		System.out.println(stu);
		stu.name = "Tom";//通过student变量的地址找到相应的对象
		stu.doHomework();
	}
}

3.用this调用构造方法

public class Student {

	int age;
	String name;

	public Student(int age) {
		this.age = age;
	}
	public Student(String name) {
		this.name = name;
	}
	public Student(int age, String name) {
		this(age);
//		Student stu = new Student(name);
//		System.err.println(stu.age);
		this.name = name;
	}
	public static void main(String[] args) {
		Student student = new Student(12, "王五");
		System.out.println(student.age);
		System.out.println(student.name);
	}
}

注:用this调用构造方法时,this只能放在构造方法第一行,只能出现一次,不能在两个构造方法中互相调用

运行结果:

注释掉两行后结果:12,王五

未注释两行,删去this.name = name后,结果:12,null,0

注意:关键字this不能在被static修改的方法中使用,因为static修饰的方法可以用类名调用,调用时不能确定是对象调用还是类调用,不能保正调用方法的一定是对象,而this只能表示对象

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值