今天复习下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: