(二)《Java编程思想》——t h i s 关键字

this 关键字(注意只能在方法内部使用)可为已调用了其方法的那个对象生成相应的句柄。可象对待其他任何对象句柄一样对待这个句柄。

package chapter4;



//: Leaf.java

// Simple use of the "this" keyword

public class Leaf {

    private 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
在构建器里调用构建器

package chapter4;



//: Flower.java

// Calling constructors with "this"

public class Flower {

    private int petalCount = 0;

    private String s = new String("null");



    Flower() {

        this("hi", 47);

        System.out.println("default constructor (no args)");

    }



    Flower(int petals) {

        petalCount = petals;

        System.out.println("Constructor w/ int arg only, petalCount= " + petalCount);

    }



    Flower(String ss) {

        System.out.println("Constructor w/ String arg only, s=" + ss);

        s = ss;

    }



    Flower(String s, int petals) {

        this(petals);

        // ! this(s); // Can't call two!

        this.s = s; // Another use of "this"

        System.out.println("String & int args");

    }



    void print() {

        // ! this(11); // Not inside non-constructor!

        System.out.println("petalCount = " + petalCount + " s = " + s);

    }



    public static void main(String[] args) {

        Flower x = new Flower();

        x.print();

    }

} // /:~

【运行结果】:

Constructor w/ int arg only, petalCount= 47
String & int args
default constructor (no args)
petalCount = 47 s = hi

this调用构建器要注意几点:

1.它会对与那个自变量列表相符的构建器进行明确的调用。

2.只能在一个构建器中使用this调用另一个构建器,不能在其他任何方法内部使用。

3.this调用构建器必须写在第一行,否则会收到编译程序的报错信息。

4.在一个构建器中不能两次使用this调用其他构建器(即与第三条相符)。

 

 

你可能感兴趣的:(java编程思想)