现在的位置: 首页 > 综合 > 正文

java中的this关键字

2017年12月05日 ⁄ 综合 ⁄ 共 934字 ⁄ 字号 评论关闭

java中的this关键字

java 私塾跟我学系列——JAVA篇  网址:www.javass.cn

关键字 this 是用来指向当前对象或类实例的,功能说明如下:

1:点取成员

this.day 指的是调用当前对象的 day 字段,示例如下:

Copy code

public class MyDate {
  private int day, month, year;
  public void tomorrow() {
    this.day = this.day + 1;
      其他代码
  }
}

Java 编程语言自动将所有实例变量和方法引用与 this 关键字联系在一起,因此,使用关键字在某些情况下是多余的。下面的代码与前面的代码是等同的。

Copy code

public class MyDate {
  private int day, month, year;
  public void tomorrow() {
    day = day + 1;  在 day 前面没有使用 this
    其他代码
  }
}

2:区分同名变量

也有关键字 this 使用不多余的情况。如,需要在某些完全分离的类中调用一个方法,并将当前对象的一个引用作为参数传递时。例如:

Birthday bDay = new Birthday (this);

还有一种情况,就是在类属性上定义的变量和方法内部定义的变量相同的时候,到底是调用谁呢?例如:

Copy code

public class Test{
  int i = 2;
  public void t(){
    int i = 3; 跟属性的变量名称是相同的
    System.out.println(“实例变量 i=”+ this.i);
    System.out.println(“方法内部的变量 i=”+ i);
  }
}

也就是说:“this.变量”调用的是当前属性的变量值,直接使用变量名称调用的是相对距离最近的变量的值。

3:作为方法名来初始化对象

也就是相当于调用本类的其它构造方法,它必须作为构造方法的第一句。示例如下:

Copy code

public class Test {
  public Test(){
    this(3);在这里调用本类的另外的构造方法
  }
  public Test(int a){
  }
  public static void main(String[] args) {
    Test t = new Test();
  } 
}

抱歉!评论已关闭.