【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();
  }
}

 

希望大家多多交流

 

转载于:https://www.cnblogs.com/jianpanaq/p/10162175.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值