黑马程序员技术交流社区

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

作者: testteam    时间: 2014-7-12 20:33
标题: this关键字
This关键字的作用

1.点取成员
This.成员属性

2.区分同名变量
在类属性上定义的变量
在方法内部定义的变量

This.变量调用的是当前属性的变量值
直接使用变量名称调用的是相对距离较近的变量的值(就是方法内部的变量)

3作为方法名来初始化对象
public class Test{
public Test()
{
    this(3); //在这里调用本类的另外的构造方法
}
Public Test(int a)
{
}
Public static void main(String[] args)
{
Test t=new Test();
}

}
4.作为参数传递


第四种是什么意思?
作者: testteam    时间: 2014-7-12 20:36
第三种里面修改      this.变量 应该说是当前对象(类)的变量值
作者: 追逐我的明天    时间: 2014-7-25 22:27
this 关键字还可以传递当前对象的内存地址:
public class lianxi2 {
                public lianxi2 show(){
                        return this;
                }
}

        public static void main(String[] args) {
                        lianxi2 a = new lianxi2();
                        System.out.println(a.show());

        }
打印结果是:练习.lianxi2@4f1d0d

作者: WJN_YES    时间: 2014-7-30 09:04
在网上找了一个参考,不知道有没有用,不过你可以看看这事网址http://blog.csdn.net/huan_mie/article/details/5908902

作者: WJN_YES    时间: 2014-7-30 09:08
把this作为参数传递
当你要把自己作为参数传递给别的对象时,也可以用this。如:
public class A {
  public A() {
    new B(this).print(); //比如这里newB(this),找到B的构造方法会发现需要A类型的参数,所以this应该表示A的一个实例化对象。
  }

  public void print() {
    System.out.println("Hello from A!");
  }
}

public class B {
  A a;
  public B(A a) {
    this.a = a;
  }

  public void print() {
    a.print();
    System.out.println("Hello from B!");
  }
}

运行结果:
  Hello from A!
  Hello from B!

作者: 黑马-胡明    时间: 2014-7-30 09:32
看到this,想到了super···




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