package com.rk.www.TestForInterView; /** * 测试构造方法的调用(this) * 要点: * 1,构造方法只能由构造方法调用,只能一次调用一个 * 2,构造方法调用只能在第一句 * * @author jacky * */ public class TestForConstructor { /** * int型成员变量 */ int petalCount = 0; /** * String型成员变量 */ String s = "initial value"; /** * 只接收int型构造方法 * * @param petals */ TestForConstructor(int petals) { petalCount = petals; System.out .println("Construnctor w/ int arg only,petalCount=" + petalCount); } /** * 只接收String型成员变量 * * @param ss */ TestForConstructor(String ss) { System.out .println("Construnctor w/ int String only,s=" + ss); } /** * 两个参数的构造方法 * * @param s * @param petals */ TestForConstructor(String s, int petals) { this(petals); /** * 不能在构造方法里面调用两次其他构造方法 */ // this(s); this.s = s; System.out .println("String & int args"); } /** * 无参数构造方法 */ TestForConstructor() { this("hi", 47); System.out .println("default constructor (no args)"); } /** * 成员方法 */ void printPetalCount() { /** * Constructor call must be the first statement in a constructor */ // this(11); System.out .println("petalCount=" + petalCount + " s=" + s); } public static void main( String[] args) { TestForConstructor testForConstr = new TestForConstructor(); testForConstr.printPetalCount(); } }