美文网首页
Think in Java(二) this关键词

Think in Java(二) this关键词

作者: 如雨随行2020 | 来源:发表于2022-01-14 13:01 被阅读0次
    1. this关键字只能在方法内部使用,表示对“调用方法的那个对象”的引用。
    2. 只要当需要明确指出对当前对象的引用时,才需要使用this关键字。例如,当需要返回对当前对象的引用时,就常常在return语句中这样写:
    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();
        }
    }
    

    由于increment()通过this关键字返回了当前对象的引用,所以很容易在一条语句里对同一个对象执行多次操作。
    另外,this关键字对于将当前对象传递给其他方法也很有用

    class Peeler {
        static Apple peel(Apple apple) {
            //... remove peel
            return apple;   //Peeled
        }
    }
    class Apple {
        Apple getPeeled() { return Peeler.peel(this); }
    }
    class Person {
        public void eat(Apple apple) {
            Apple peeled = apple.getPeeled();
            System.out.println("oishi");
        }
    }
    public class PassingThis {
        public static void main(String[] args) {
            new Person().eat(new Apple());
        }
    }
    
    1. 在构造器中调用构造器

    有时候想在一个构造器中调用另一个构造器,以避免重复代码。可用this做到

    public class Flower {
        int petalCount = 0;
        String s = "initial value";
        Flower(int petal) {
            petalCount = petal;
            print("Constructor with int arg only, petalCount=" + petalCount);
        }
        Flower(String s) {
            print("Contructor with String arg only, s = " + s);
            this.s = s;
        }
        Flower(String s, int petal) {
            this(petal);
            this.s = s;
            print("String & int args");
        }
        Flower() {
            this("hi", 47);
            print("default constructor (no args)");
        }
        void printPetalCount() {
            print("petalCount = " + petalCount + " s = " + s);
        }
        public static void main(String[] args) {
            Flower x = new Flower();
            x.printPetalCount();
        }
        /* Output:
        Constructor with int arg only, petalCount = 47
        String & int args
        default constructor(no args)
        petalCount = 47 s = hi
        */
    

    说明:1)用this可以调用一个构造器,但不能调用两个。
    2)必须将构造器调用置于最起始处,否则编译器会报错
    3)除构造器之外,编译器禁止在其他任何方法中调用构造器

    相关文章

      网友评论

          本文标题:Think in Java(二) this关键词

          本文链接:https://www.haomeiwen.com/subject/dkyraltx.html