this可能是几乎所有有一点面向对象思想的语言都会引用到的变量,java自然不例外。只是,this有多少种用法,我也不知道了,让我们来see see。

由简入奢! 易。

来个例子说明下:

public class DebugerTest {
  public static void main(String[] args) {
    UserExample samp1 = new UserExample("amy");
    System.out.println("who are u? ");
    System.out.println(samp1.whoAreU());
    System.out.println("intro yourself?");
    System.out.println(samp1.introYourself());
  }
}
class UserExample {
  private String name;
  private Integer age;
  private MyDoll myDoll;
  public UserExample() {
    this(null);
  }
  // 3. 调用本类的其他构造方法
  public UserExample(String name) {
    this(name, -1);
  }
  public UserExample(String name, Integer age) {
    this.name = name;
    this.age = age;
    this.myDoll = new MyDoll("prize");
  }
  // 2. 调用本类属性
  public void changeMyName(String name) {
    this.name = name;
  }
  public void changeMyAge(Integer age) {
    this.age = age;
  }
  public String whoAreU() {
    return "I am " + name + ". ";
  }
  public String haoOldAreU() {
    return "i am " + age + " old.";
  }
  // 1. 调用本类方法
  public String introYourself() {
    return this.whoAreU() +
        this.haoOldAreU() +
        "\r\n whoAmI@ " + this.myDoll.whoAmI() +
        "\r\n whoAreSuper@ " + this.myDoll.whoAreSuper();
  }
  class MyDoll {
    private String name;
    public MyDoll(String name) {
      this.name = name;
    }
    public void changeMyName(String name) {
      this.name = name;
    }
    // 5. 隐藏式的调用
    public String whoAmI() {
      return whoAreU();
    }
    public String whoAreU() {
      return "I am a Doll, my name is " + name + ". ";
    }
    // 4. 调用父类的或指定的其他的类的同名方法
    public String whoAreSuper() {
      return "super is " + UserExample.this.whoAreU() + ". ";
    }
  }
}

1. 调用本类方法,表达更清晰

  public String introYourself() {
    return this.whoAreU() + this.haoOldAreU();
  }

2. 调用本类属性,基本功亮出来

  public void changeMyName(String name) {
    this.name = name;
  } 

3. 调用本类的其他构造方法,更灵活

  public UserExample(String name) {
    this(name, -1);
  }

4. 调用父类的或指定的其他的类的同名方法,为避免歧义而生的方法

    public String whoAreSuper() {
      return "super is " + UserExample.this.whoAreU() + ". ";
    }

5. 隐藏式的调用,为了写代码方便(更常用),不指定范围,java会在全类范围内向上查找变量或方法   

public String whoAmI() {
      return whoAreU();
    }

以上样例输出结果如下所示:

  this是个基本的关键字,我们平时也一直在用,只是也不一定所有同学都清楚怎么用。

收藏 打印