java 构造器中调用构造器

//:object/Practice.java
/**Calling constructors with "this"
 * @author Female_
 * */
public class Practice {
   int petalCount=0;
   String s ="initals value";
   Practice(int petals){
   petalCount = petals;
   System.out.println("Constructor w/ int arg only, petalCount= "+petalCount);
   }
   Practice(String ss){
   System.out.println("Constructor w/ String arg only ,s= "+ss);
   s=ss;
   }
   Practice(String s,int petals){
   this(petals);
   // !this(s);    不能用this调用两个构造器,且必须将构造器置于最起始处
   this.s=s;
   System.out.println("String & int args");
   }
   Practice(){
   this("hi",47);
   System.out.println("default constructor (no args)");
   }
   void printPetalCount() {
   //! this(11);   除构造器之外,编译器禁止在其他任何方法中调用构造器
   System.out.println("petalCount= "+petalCount+" s= "+s);
   }
public static void main(String[] args) {
Practice a=new Practice();
a.printPetalCount();
}
}/*Ouput:
Constructor w/ int arg only, petalCount= 47
String & int args
default constructor (no args)
petalCount= 47 s= hi
*/

你可能感兴趣的:(java)