java this 关键字

    技术2022-05-19  22

    22:43:152011-04-18                                                                    java 关键字    this 关键字:  用法1:仅仅用于方法内部使用,表示对“调用方法的对象”的引用。 例如:   public class Leaf{      int i=0;      Leaf  intem(){        i ;        return this;   }    void print()[     System.out.println("i=" i);  }    public static void main(String[] args){    Leaf x=new Leaf();   x.intem().intem().intem().print(); } }  output    i=3  由于intem()通过this关键字 返回了对当前对象的引用,则很容易在一条语句里对同一对象的多次操作。 用法2:隐藏变量,此用法用于当参数列表传递参数的名称与定义的变量名称相同时,使用this可隐藏变量。  列子: class banan{        int i=1;     String str="ste";    banan(int i,String str){     this.str=str;   this.i=i;  }  public int f(){   return i;  }  public String g(){   return str;  }   public static void main(String[] args){  banan ban=new banan(55,"qwe");  System.out.println("i:" ban.f());  System.out.println("str:" ban.g());  } }///output i:55 str:qwe  这里在banan中定义了变量i  str 然而传递的参数 也是i  str  所以使用 this 隐藏数据成员。。若不用this则输出程序开始定义的变量值。。。 用法3: 在构造器中调用构造器(注意与“super”关键字的区别,super将在后面的文章中介绍) this能调用构造器 且仅能调用一次,使用this时必须是第一行语句。否者不能编译。。。 例子:     class banan{        int i=1;     String str="ste";  banan(int i){   this.i=i;  }  banan(String str){   this.str=str;  }  banan(int i,String str){     this(str);   this.i=i;  }  public int f(){   return i;  }  public String g(){   return str;  }   public static void main(String[] args){  banan ban=new banan(55,"qwe");  System.out.println("i:" ban.f());  System.out.println("str:" ban.g());  } }output i:55 str:qwe 这里通过banan ban=new banan(55,"qwe");来调用构造器banan(int i,String str) 在这个构造其中我们要调用构造器banan(int i) 所以使用this(str) 注意这里面用到了用法2中的 this的用法。。请仔细回味。。        好了 this关键字就这么多内容,本人学的不是很好,如过有错误的地方 请予以指出  欢迎大家的批评。。。。      再次感谢《Thinking in java》的作者,本文内容部分出自于此  


    最新回复(0)