码迷,mamicode.com
首页 > 编程语言 > 详细

Java - this的使用方法

时间:2017-07-10 14:23:12      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:data-   []   使用   返回   ring   default   const   markdown   down   

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
 *///:~

技术分享

Java - this的使用方法

标签:data-   []   使用   返回   ring   default   const   markdown   down   

原文地址:http://www.cnblogs.com/mfmdaoyou/p/7145381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!