java中this关键字

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());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值