【JAVA】this的3个应用方式

今天复习下this的3个用法,以后遇到有新的用法再补充:

this

1.数据传递,比如:

public class dog{
	int age;
	public example(int age){
		this.age = age; 
		//这时候this.age代表的是上方刚刚的age,等于号后面的age是后面输入的参数age;
	}
}

2.调用外类的方法,比如:

public class teacher{
	teacher(String lecture){
		System.out.print("The teacher teaches ");
		this.teach(lecture);
	}
	public void teach(String lecture){
		System.out.println(lecture+".");
	}
	public static void main(String[] args){
		new teacher("Chinese");
	}
}

3.把自己当作参数传递,比如

class A(){
	A(){
		new B(this).print;
	}
	public void print(){
		System.out.println("从A调用“);
	}
}
class B(){
	A a;
	B(A a){
		this.a = a;
	}
	public void print(){
		a.print();
		System.out.println("从B调用“);
}
public class PrintAB(){
	A aaa = new A(); 				//这里使用了Class A的构造函数A()
	aaa.print(); 					//这里使用了Class A的print()函数
	System.out.println("pause.");
	B bbb = new B(); 				//这里使用了Class B的构造函数B()
	bbb,print(); 					//这里使用了Class B的print()函数
}

Output:
output

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值