1. 程式人生 > >java this 3種常見用法 詳解

java this 3種常見用法 詳解

1.區分成員變數和區域性變數

public class ThisDemo {
        public static void main(String[] args) {
            Student s=new Student("小明明",20);
            System.out.println(s);
        }
    }
    class Student{
        String name;
        int age;
        public Student(String name, int age) {
            //注:沒有加this
name = name; age = age; } @Override public String toString() { return "Student [ name=" + name + ", age=" + age +"]"; } }
列印結果:Student [ name=null, age=0]
賦值沒有成功,說明:name(區域性變數)=name(區域性變數);
而不是name(成員變數)=name(區域性變數);

public Student(String name, int age) {
        //注:可以使用this進行區分成員變數和區域性變數
        this.name = name;
        this.age = age;
}
列印結果:Student [ name=小明明, age=20]
這樣子就可以賦值成功啦

2.代表當前物件

public static void main(String[] args) {
            Student s=new Student("小明明",20);
            System.out.println(s);
    }
    //為什麼加入this後就可以區分呢?
    因為this當前代表的是s例項(物件)相當於
    s.name="小明明";
    s.age="20";
    //再可以理解如下
    this.name=例項(物件).name="小明明"

3.構造器與構造器之間的呼叫

為Student再新增兩個構造器,修改後如下:
    class Student{
        String name;
        int age;
        int id;

        public Student(int id,String name, int age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }


        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public Student(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Student [ id=" + id + ", name=" + name + ", age=" + age +"]";
        }
    }
//構造器用法-->this();跟函式一樣()中可以寫引數
構造器呼叫一般是這樣子用的.不同的構造器中存在相同程式碼.為了複用性。可以在引數少的構造器中呼叫引數多的構造器,如下:
class Student{
        String name;
        int age;
        int id;
        public Student(String name, int age, int id) {
            this.name = name;
            this.age = age;
            this.id = id;
            System.out.println("構造器3已呼叫");
        }
        public Student(String name, int age) {
            this(name,age,0);
            System.out.println("構造器2已呼叫");
        }

        public Student(String name) {
            this(name,0);//引數不足,就使用引數預設值補全
            System.out.println("構造器1已呼叫");
        }
        @Override
        public String toString() {
            return "Student [ id=" + id + ", name=" + name + ", age=" + age +"]";
        }
    }
測試結果1:
    public static void main(String[] args) {
        Student s=new Student("小明明");
        System.out.println(s);
    }   

    構造器3已呼叫
    構造器2已呼叫
    構造器1已呼叫
    Student [ id=0, name=小明明, age=0]

測試結果2:
    public static void main(String[] args) {
        Student s=new Student("小明明",20);
        System.out.println(s);
    }
    構造器3已呼叫
    構造器2已呼叫
    Student [ id=0, name=小明明, age=20]

總結:這樣子可以在引數最多的構造器中編寫代表。其他構造器負責呼叫引數最多的那個構造器就好了
this的三種常見用法介紹完畢!怎麼用很容易吧.