黑马程序员技术交流社区

标题: this 关键字小问题 [打印本页]

作者: 庄星睿    时间: 2012-6-12 17:04
标题: this 关键字小问题
学到后边了,回过头来在做前面的小练习也蒙了:
  1. class A
  2. {
  3. private B b=null;
  4. public void fun()
  5. {
  6. this.b=new B(this);
  7. this.b.fun();

  8. }
  9. public void print()
  10. {
  11. System.out.println("Hello World!!!");
  12. }

  13. }

  14. class B
  15. {
  16. private A a=null;
  17. public B(A a)
  18. {
  19. this.a =a;
  20. }
  21. public void fun()
  22. {
  23. this.a.print();
  24. }

  25. }


  26. public class ThisDemo2
  27. {
  28. public static void main(String[] args)
  29. {
  30. new A().fun();
  31. new B(new A()).fun();
  32. }
  33. }
复制代码
输出结果都是:
Helloworld!
Helloworld!
new B(new A()).fun()还好理解一点,匿名对象参数传递,函数调用
new A().fun(); 其中this .b=new B(this);this 代表当前对象了,把当前对象传进去,this.b.fun()实际上相当于还是调用当前对象的方法

作者: 郑传庆    时间: 2012-6-12 17:16
this就是指像对象本身的一个指针,但this不能用在静态的方法中。
作者: 李海晓    时间: 2012-6-12 17:35
本帖最后由 李海晓 于 2012-6-12 17:36 编辑

this .b=new B(this);这个this传递的是自己的引用,也就是Class A,this.a =a;将this的引用赋予Class B中的变量a。接着执行Class B中的public void fun(){this.a.print();}。调用Class A中的public void print(){System.out.println("Hello World!!!");}
打印出Hello World
作者: 郭永岳    时间: 2012-6-12 19:23
首先你要理解this的用法
1、this指的就是当前对象(类的实例)。
2、假设A类有一个f()方法,里面用到了this。
那么
A a1 = new A();
A a2 = new A();
a1.f(); // 里面的this就是指当前对,即a1。
a2.f(); // 里面的this就是指当前对,即a2。

3、所以静态static方法中不能用this,因为this指的是当前对象,而静态方法调用是不用创建对象的。






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2