搜索

java中的this关键字

[复制链接]
查看: 2148|回复: 0
发表于 2010-12-13 09:25:48 | 显示全部楼层 |阅读模式 来自 中国北京来自: 中国北京
java中的this关键字

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

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

1:点取成员

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

  1. public class MyDate {
  2.   private int day, month, year;
  3.   public void tomorrow() {
  4.     this.day = this.day + 1;
  5.       其他代码
  6.   }
  7. }
复制代码
Java 编程语言自动将所有实例变量和方法引用与 this 关键字联系在一起,因此,使用关键字在某些情况下是多余的。下面的代码与前面的代码是等同的。

  1. public class MyDate {
  2.   private int day, month, year;
  3.   public void tomorrow() {
  4.     day = day + 1;  在 day 前面没有使用 this
  5.     其他代码
  6.   }
  7. }
复制代码
2:区分同名变量

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

Birthday bDay = new Birthday (this);

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

  1. public class Test{
  2.   int i = 2;
  3.   public void t(){
  4.     int i = 3; 跟属性的变量名称是相同的
  5.     System.out.println(“实例变量 i=”+ this.i);
  6.     System.out.println(“方法内部的变量 i=”+ i);
  7.   }
  8. }
复制代码
也就是说:“this.变量”调用的是当前属性的变量值,直接使用变量名称调用的是相对距离最近的变量的值。

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

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

  1. public class Test {
  2.   public Test(){
  3.     this(3);在这里调用本类的另外的构造方法
  4.   }
  5.   public Test(int a){
  6.   }
  7.   public static void main(String[] args) {
  8.     Test t = new Test();
  9.   }   
  10. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

精华帖子
热门图文
快速回复 返回顶部 返回列表