Java中this的使用方法

来源:互联网 发布:淘宝旧版本4.0.0下载 编辑:程序博客网 时间:2024/05/01 08:34
使用this关键字的情形
 1.构造函数中

  可以使用"this(参数)"形式调用其它构造函数。 而不能直接调用  "构造函数名(参数)"  去调用其他构造函数。

  注意:这个参数必须是在调用这个构造函数之前就已经存在的。例子:

class Square{   private double border;   public Square()   {         this(border);   //这里出错   是因为这里border被定义为实例变量,在调用构造函数创建实际对象之前,他是不存在的
                         // 若改为    private static double border; 则程序运行正确
                         // 若改为  test(border); 也将编译报错   }
   public Square(double border)   {         System.out.println(border);   }}


 2.普通函数中
  this代表调用当前函数的对象

  通常在set方法和构造函数中都会使用, 当局部变量和成员变量同名时访问成员变量(因为成员变量会被局部变量覆盖

public class test {static int i; static String str;public test(){this(i,str);}public test(int i, String str){this.i = i;str = str;    //这里没有使用this 关键字}public static void main(String[] args){int i=2;test t = new test(i,"kk");System.out.println(t.i);      //输出为2System.out.println(t.str);    //输出为null}}



 3.内部类中

  访问外部类的成员时,使用"外部类名.this.成员名"进行访


 4.代表调用对象本身.

class AA {       String name;              public AA(){           System.out.println("1无参构造.....");           System.out.println(this); // 打印的是对象a的内存地址.      }              public void play(){           System.out.println("游戏人生........");       }              public static void main(String[] args) {         AA a = new AA();       }   }  





0 0