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

来源:互联网 发布:服务器 定时关机 软件 编辑:程序博客网 时间:2024/06/06 05:56

用途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 = Mikethis.age = 17【无参数】的构造方法测试如下:this.name = nihaothis.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