Java 基础(3) —— this 的用法

用途1:在类里面来引用这个类的属性

this 对象,它可以在类里面来引用这个类的属性和方法。

this 关键字是类内部当中对自己的一个引用,可以方便类中方法访问自己的属性


public class thisDemo_1 {
    String name = "Mick";

    public void print(String name) {
        // this 对象,它可以在类里面来引用这个类的属性和方法
        System.out.println("类中的属性 this.name = " + this.name);
        System.out.println("局部传参的属性 name = " + name);
    }

    public static void main(String[] args) {
        thisDemo_1 tt = new thisDemo_1();
        tt.print("Orson");
    }
}
类中的属性 this.name = Mick
局部传参的属性 name = Orson

用途2:在一个构造函数中,通过this来调用另一个构造函数

一个类中定义两个构造函数,在一个构造函数中通过 this 来调用另一个构造函数

无参数构造方法中调用有参数构造方法

public class Dog {
    private String name;
    private int age;

    // 有参数的构造方法
    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println("this.name = " + this.name);
        System.out.println("this.age = " + this.age);
    }

    // 这个无参构造方法里调用的有参数的构造方法,这个也就是this的第二种用法了!
    public Dog() {
        this("nihao", 20);
    }

    public static void main(String[] args) {
        System.out.println("【有参数】的构造方法测试如下:");
        Dog has_args = new Dog("Mike", 17);

        System.out.println("【无参数】的构造方法测试如下:");
        Dog no_args = new Dog();
    }
}
【有参数】的构造方法测试如下:
this.name = Mike
this.age = 17
【无参数】的构造方法测试如下:
this.name = nihao
this.age = 20

有参数构造方法中调用无参数构造方法

public class ThisDemo_3 {
    String name;
    int age;

    public ThisDemo_3() {
        this.age = 21;
    }

    public ThisDemo_3(String name, int age) {
        this();
        this.name = "Mick";
    }

    private void print() {
        System.out.println("最终名字=" + this.name);
        System.out.println("最终的年龄=" + this.age);
    }

    public static void main(String[] args) {
        ThisDemo_3 tt = new ThisDemo_3("Mick", 0); // 随便传进去的参数
        tt.print();
    }
}
最终名字=Mick
最终的年龄=21

用途3:通过 this 返回自身这个对象

通过this 关键字返回自身这个对象然后在一条语句里面实现多次的操作

public class ThisDemo_2 {
    int number = 0;

    ThisDemo_2 increment() {
        number++;
        return this;
    }

    private void print() {
        System.out.println("number=" + number);
    }

    public static void main(String[] args) {
        ThisDemo_2 tt = new ThisDemo_2();
        tt.increment().increment().increment().print();
        System.exit(0);
    }
}
number=3
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值