java中this关键字的用法

通常写this的时候,都是指“这个对象”或者“当前对象”,而它本身表示对当前对象的引用。

1.当成员变量名与局部变量名相同时,会产生歧义,此时用 this.成员变量名 表示成员变量

public class ThisDemo01{
	String name = "Jack";
	public void print(String name){
		System.out.println("局部变量值  = "+name);
		System.out.println("成员变量值 = "+this.name);//this.name表示成员变量
		this.name = name;
		System.out.println("改变成员变量后 = "+this.name);
	}
	public static void main(String[] args){
		ThisDemo01 td = new ThisDemo01();
		td.print("Rose");
	}
}

输出结果:

局部变量值  = Rose
成员变量值 = Jack
改变成员变量后 = Rose

2.通过this关键字将当前对象传递给其他方法
class Water{
	public Water(){
		new Person().drinkWater(this);
	}
}
class Person{
	public void drinkWater(Water wt){//将Water对象传递过来
		System.out.println("喝水成功");
	}
}
public class ThisDemo02{
	public static void main(String[] args){
		new Water();
	}
}
3.在构造方法中调用另一个构造方法
class Person{
	String name;
	int age;
	public Person(String name){
		this.name = name;
	}
	public Person(String name,int age){
		this(name);
		this.age = age;
	}
	public void print(){
		System.out.println("姓名:"+name+" 年龄: "+age);
	}
}
public class ThisDemo03{
	public static void main(String[] args){
		Person per = new Person("Jack",30);
		per.print();
	}
}
4.在内部类或匿名内部类中调用外部类方法,有两种情况

第一种:外部类、匿名内部类两者没有重名方法,则内部匿名类自动获得外部类的成员变量和方法的调用权限

第二种:外部类、匿名内部类两者有重名方法,则通过this可以获取外部类的重名方法

public class ThisDemo04{
	public void run(){
		System.out.println("我是外部类run方法");
	}
	public ThisDemo04(){
		Thread thread = new Thread(){
			public void run(){
				<span style="color:#ff0000;"><strong>ThisDemo04.this.run();</strong></span>
				System.out.println("我是内部类run方法");
			}
		};
		thread.start();
	}
	public static void main(String[] args){
		new ThisDemo04();
	}
}
除此之外,还可以将外部类run()声明成static,这样内部类可以直接调用。
public class ThisDemo04{
	public<span style="color:#ff0000;"><strong> static</strong></span> void run(){
		System.out.println("我是外部类run方法");
	}
	public ThisDemo04(){
		Thread thread = new Thread(){
			public void run(){
				<span style="color:#ff0000;"><strong>ThisDemo04.run();</strong></span>
				System.out.println("我是内部类run方法");
			}
		};
		thread.start();
	}
	public static void main(String[] args){
		new ThisDemo04();
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值