【JAVA】this关键字

前言

最近在看多线程时,在线程调用getName()方法时发现this关键字,这半年来,入坑了外包,面试java,进公司后做了运维维护,天天在熟悉linux命令,现在就来回顾下this关键字。先来看一段代码。

public class Demo1 {
  String s = "Hello";

  public Demo1(String s) {
    System.out.println("the first s :  " + s);
    System.out.println("the second s : " + this.s);
    this.s = s;
    System.out.println("the third s : " + this.s);
  }

  public static void main(String[] args) {
    Demo1 d = new Demo1("HelloWorld!");
    System.out.println("the fourth s : " + d.s);
  }
}

自己可以执行以下,如果跟预想不一样的话,就继续往下看吧。

1.this可以用来修饰成员变量

以前言中的代码为例,String s = "Hello"是成员变量,则this.s是指"Hello",而s是指局部方法,即public Demo1(String s) 的s,所以

the first s: HelloWorld      the second s : Hello    

this.s是指 将public Demo1(String s) 的s的值赋予成员变量的s,所以String s = "Hello"的值从"Hello"变成"HelloWorld"

the third s : HelloWorld     the fourth s : HelloWorld

2.this可以用来调用普通方法

public class Test2{

  public static void main(String[] args) {
    Test2 t2 = new Test2();
    t2.test();
  }

  public void test() {
    this.getTest();
  }

  public void getTest() {
    System.out.println("test");
  }
}

3.this调用构造方法

public class Test3 {

  public String name;
  public int gender; //1代表男 2代表女

  public Test3() {
    this("未知", 1);
  }

  public Test3(String name, int gender) {
    this.name = name;
    this.gender = gender;
  }

  public static void main(String[] args) {
    Test3 t3 = new Test3();
    System.out.println(t3.name);
    System.out.println(t3.gender);
  }

}

4.this调用当前对象

这个不是太常用,了解下就好

class BlueMoon {
  public void print() {
    //哪个对象调用了print()方法,this就自动与此对象指向同一块内存地址
    System.out.println("this=" + this);//this 就是当前调用对象
  }
}

public class Test4 {

  public static void main(String[] args) {
    BlueMoon bm = new BlueMoon();
    BlueMoon bm2 = new BlueMoon();
    System.out.println("bm=" + bm);
    bm.print();
    System.out.println("---------------------");
    System.out.println("bm2=" + bm2);
    bm.print();
  }
}

希望大家多多交流

Ride the wave as long as it will take you.
原文地址:https://www.cnblogs.com/jianpanaq/p/10162175.html