JAVA review of this keyword

I. Overview

       this represents the object it refers to the function belongs in. Which team is like this where the function is called, this on behalf of which object.

Second, the use of

       this keyword has three main applications.

       1, this call this class of property, which is a member variable class. 

       Dog.java

public class Dog {
    public String name;

    public void getName(){
        System.out.println(this.name);
    }
}

       Demo1.java

public class Demo1 {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.name = "大黄";
        System.out.println(dog.name);
    }
}

       2, this call other methods in this class.

       Demo2.java

public class Demo2 {
    public static void main(String[] args) {
        new Demo2().aaa();
    }

    public void aaa(){
        this.bbb();
    }

    public void bbb(){
        System.out.println("这是bbb");
    }
}

     3, this call other constructor in this class, to put the first line of the constructor when calling.

     Demo3.java

public class Demo3 {
    public Demo3() {
        this("大黄");
    }

    public Demo3(String name){
        System.out.println("这里是" + name);
    }
}

     Demo4.java

public class Demo4 {
    public static void main(String[] args) {
        Demo3 demo3 = new Demo3();
    }
}

 

Released three original articles · won praise 0 · Views 53

Guess you like

Origin blog.csdn.net/weixin_45585434/article/details/104074930