public class Test {
private String name = "张三";
private int age;
private String address = "shanghai";
private String tel = "17302012501";
public Test() {
this("王五", 25); //2.this(...);调用有参构造函数
Test test1 = this; //5.this关键字把当前对象传递给其他对象(就算在其他方法中(不是构造方法)也是值得是当前对象)
System.out.println(test1.age);//输出25
}
public String getAddress() {
return address;
}
//1.this.变量名:重名时调用该方法所在类中的成员变量
public Test(String name, int age) {
System.out.println("name=" + name);//输出name=王五
System.out.println("1->this.name=" + this.name);//输出1->this.name=张三
this.name = name;
this.age = age;
System.out.println("2->this.name=" + this.name);//输出2->this.name=王五
}
public void eat() {
System.out.println("He is eating");
}
public void run() {
this.eat(); //4.this.成员方法: 调用本类的成员方法
System.out.println("He is running");
}
public void showTest(Test tst) {
System.out.println(name + "..." + age); //输出王五...25
}
public void show() {
showTest(this); //3.this:表示当前对象的引用.谁来调用我,我就代表谁
}
//Student stu = new Student(this);
//stu.info();
public void stu() {
Student stu = new Student(this);//this关键字把当前对象传递给其他对象(就算在其他方法中(不是构造方法)也是值得是当前对象)
stu.info();
}
public static void main(String[] args) {
Test test = new Test();
test.run();
test.eat();
test.show();
//Student stu = new Student(this);
//stu.info();
test.stu();
}
}
class Student {
Test t;
public Student(Test test) {
this.t = test;
}
public void info() {
System.out.println(t.getAddress());
}
}
java中this关键字
最新推荐文章于 2021-10-20 23:00:35 发布