首页 > 学院 > 开发设计 > 正文

Java学习之This的用处

2019-11-18 11:48:50
字体:
来源:转载
供稿:网友

  This是什么东西?对于从来没有学过面向对象语言的我来讲,是一件新鲜的事物,不过,它的用处到还挺多的。
  
  首先来看一个程序:
  
  public class Date
  
   {
  
      PRivate int day=1;
  
      public void tomorrow()
  
      {
  
         this.day = this.day + 1;
  
         System.out.println("day="+this.day);
  
      }
  
      public static void main(String args[])
  
      {
  
         Date date=new Date();
  
         date.tomorrow();
  
      }
  
  }
  
  这个程序的输出是“day=2”this实际上就是得到当前所在类的句柄,可以通过这个句柄对它的属性和方法进行操作。其实在上面的例子中,假如把this去掉,程序所得到的结果和上面这个程序所得到的结果是一样的。这是由于编译器可以自动完成默认的识别。那么看下面这个程序,只不过把上面的程序稍加改动,this的有无对程序有没有影响?
  
  public class Date
  
   {
  
      private int day=1;
  
      public void tomorrow(int day)
  
      {
  
         day = day + 1;
  
         System.out.println("day="+day);
  
      }
  
      public static void main(String args[])
  
      {
         Date date=new Date();
  
         date.tomorrow(2);
  
      }
  
  }
  同样的执行程序,会得到和上面程序不同的结果,它将会得到“day=3”这是因为此时产生了重名,在tomorrow这个函数中有了一个参数,也叫day,假如不使用this,直接使用day,java将认为是使用的这个参数,而不是类中所定义的私有变量day,假如要使用这个私有变量,就要用this来制定所用的这个day是类中所定义的,而不是函数中的参数。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表