Java - this的用法

来源:互联网 发布:通用电气矩阵 编辑:程序博客网 时间:2024/06/05 10:18

this在内部获得当前对象的引用时调用:
(1) return返回当前对象;
(2) 构造器调用另一个构造器, 带参数;
(3) 参数的名称和数据成员的名称相同;
注意:
this构造器在方法中只能调用一次;
非构造器不能调用带参数的this.

//:Flower.java/** * 构造器 * * Created by C.L.Wang on 15/7/12. */public class Flower {    int petalCount = 0;    String s = "initial value";    Flower(int petals) {        petalCount = petals;        System.out.println("int arg only, petalCount = " + petalCount);    }    Flower(String ss) {        s = ss;        System.out.println("String arg only, petalCount = " + s);    }    Flower(String s, int petals) {        this(petals);        this.s = s;        System.out.println("String & int args");    }    Flower() {        this("hi", 47);        System.out.println("default construction (no args)");    }    void printPetalCount() {        System.out.println("petalCount = " + petalCount + " s = " + s);    }    public static void main(String[] args) {        Flower x = new Flower();        x.printPetalCount();    }}/** * Output: int arg only, petalCount = 47 String & int args default construction (no args) petalCount = 47 s = hi *///:~

娱乐

2 0
原创粉丝点击