首页 > 代码库 > Java - this的使用方法

Java - this的使用方法

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

技术分享

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

Java - this的使用方法