this指针指向函数的当前对象,这个对象是必须是类的实例和类的成员吗?还是函数内部的任何成员都可以?

解决方案 »

  1.   

    参见下面例子:class Leaf
    {
      public static int count=0;
      public int no;
      
      public Leaf()
      {
        count++;
        no=count;
      }
      
      public Leaf getObj()
      {
        return this;
      }
    }public class test
    {
      public static void main(String[] args) //throws Exception
      {
        Leaf a1 = new Leaf();
        Leaf a2 = new Leaf();
        Leaf a3;
        
        a3 = a1.getObj(); //此时this代表a1对象
        System.out.println("a1.no="+a1.no+",a3.no="+a3.no);
        a3 = a2.getObj(); //此时this代表a2对象
        System.out.println("a2.no="+a2.no+",a3.no="+a3.no);
        
        
      }
    }运行结果
    a1.no=1,a3.no=1
    a2.no=2,a3.no=2
      

  2.   

    返回的是Leaf的实例
    关键字this就是指类本身
    public class A 
    {
      String sss=null;
      public String methodA(String bb){
      this.sss=bb
      return sss;
      }
    }
    这个例子中,我们首先在类中定义一个String为sss;然后在methodA中,this.sss就是把把参数bb的值传给sss,也就是说this指向了当前的类A,而这个类又有属性sss,我们就把bb传给了它(不知道说得清楚没:P,个人表达能力不怎么样)
      

  3.   

    我知道的this有两种用途:
    其一,调用同名构造方法(这种说法比较C)。举个例子:
    class A {
       public A() {
          this(null);
       }
       public A(String param) {
       ...
       }
    }
    实现了不同参数的重载。
    其二,是实例对象本身。举个例子。
    public class B {
       int value = -1;
       public B (int value) {
          System.out.println("Before:\t" + value + "\t" + this.value);
          this.value = value;
          System.out.println("Before:\t" + value + "\t" + this.value);
       }
       public static void main(String args[]) {
          B b = new B(3);
       }
    }
    看看结果吧,就会发现这个value属性是b这个对象的,而没有用this.的这个value是通过参数表传过来的,这两个变量虽然同名,但并不相同。你程序中的this就属于这个性况,即返回实例本身。
      

  4.   

    呵呵。
    打错字了,最后一行中的“性况”应该是“情况”。第二个输出中应该是"After:\t"而不应是"Before:\t"。唉,老矣,老矣。