this关键字浅谈

this表面意思是“这个”,在JAVA中表示对“调用方法的那个对象”的引用,只能在方法内部使用,主要的用法有以下几点:
  • 返回对当前对象的引用,使得可以在一条语句对同一个对象执行多次。
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();
    }
}

output: i = 3;

  • 将当前对象传给其他方法
class Person{
    public void eat(Apple apple){
        Apple peeled = apple.getPeeled();
        System.out.println("Yummy!");
    }
}
class Peeler{
    static Apple peel(Apple apple){
        //...remove peel
        return apple
    }
}
class Apple{
    Apple.getPeeled(){ 
        return Peeler.peel(this);
    }
}

public class PassingThis{
    public static void main(String[] args){
        new Person().eat(new Apple());
    }
}

Output: Yummy;

  • 在构造器中调用构造器
public class Flower{
    int petalCount = 0;
    String s = "initial value";
    Flower(int petals){
        petalCount = petals;
        print("Constructor w/ String arg only.petalCount = " + petalCount);
    }
    Flower(String ss){
        print("Constructor w/ String arg only.ss = " + s);
    }
    Flower(String ss,int petals){
        this(petals);//只能调用一个构造器,且要在第一行
        this.s = s;//初始化实例变量
        print("String & int args");
    }
    Flower(){
        thhis("hi",47);
        print("default constructor (no args)");
    }
    void printPetalCount(){
        //! this(11)  不在在非构造器内调用
        print("petalCount = " + petalCount + "s = " + s);
    }
    public static void main(String[] args){
        Flower x = new Flower();
        x.printPetalCount();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_19894073/article/details/78661336