java关键字——this

来源:互联网 发布:网络雨晴引导员 编辑:程序博客网 时间:2024/05/22 12:18

this表示对“调用方法的那个对象”的引用。它只能在方法内部使用。this的用法和其他对象引用并无不同。

一.主要用法:
     1)表示对当前对象的引用!
     2)表示用类的成员变量,而非函数参数。
     3)在构造器中调用构造器。
1)对当前对象的引用
     在java编程思想(Thinking in Jaba)中有这么一个例子:

public class Leaf{      int i=0;      Leaf increment(){          i++;          return this;      }       void print(){           System.out.println("i = "+i);       }       public static void main(String[] args){             Leaf x=new Leaf();             x.increment().increment().increment().print();       }}
输出:i =3

   由于increment()通过this关键字返回了对当前对象的引用,所以很容易在一条语句里对同一个对象执行多次操作。

this关键字对于将当前对象传递给其他方法也很有用。

class person{    public void eat(Apple apple){          Apple peeled =apple.getPeeled();          System.out.println("Yummy");    }}class Peeler{    static Apple peel(Apple apple){         //。。。。         return apple;    }}class Apple{     Apple getPeeled(){           return Peeler.peel(this);     }}public class PassingThis{      public static void main(String[] args){            new Person.eat(new Apple());       }}输出:Yummy
   Apple需要调用Peeler.peel()方法,它是一个外部的工具方法,为零将其自身传递给外部方法,Apple必须使用this关键字。

2)调用类的成员变量。

public class Flower{int petalCount =0;String s="initial value";Flower(){this("hi",47);System.out.println("default constructor(no args)");}Flower( int petals){petalCount=petals;System.out.println("constructor int arg only,petalCount="+petalCount);}Flower( String ss){System.out.println("constructor String arg only,s="+ss);}Flower(String s,int petals){this(petals);//调用构造方法必须放在最起始处。//this(s);    不能调用构造方法两次。this.s=s;  System.out.println("String &int args");}void printPetalCount(){//this.s(11);System.out.println("petalCount="+ PetalCount +" s= "+s);}public static void main(String[] args){Flower x=new Flower();x.printPetalCount();}}
   在方法Flower(String s,int petals)中,形式参数和成员变量s会有冲突,所以我们可以使用this.s表示类的成员变量,而“=”后面的s则是方法中的参数,这样就可以将参数赋值给成员变量了。在java代码中经常出现这种写法。

3)构造器中调用构造器

   构造器不会的可以看这里(点击打开链接),在方法Flower(String s,int petals)中this(petals)调用构造方法,它必须放在最起始处。并且在一个构造方法中最多只能调用其他的构造方法一次,如果写两个的话,编译就会出错。




0 0
原创粉丝点击