日期:2014-05-20  浏览次数:20707 次

java构造函数问题
public class Flower {
  private int petalCount = 0;
  private String s = new String("null");
  Flower(String ss) {
  System.out.println(
  "Constructor w/ String arg only, s=" + ss);
  s = ss;
  }
  Flower(int petals) {
  petalCount = petals;
  System.out.println(
  "Constructor w/ int arg only, petalCount= "
  + petalCount);
  }
  
  Flower(String s, int petals) {
  this(petals);
//! this(s); // Can't call two!
  this.s = s; // Another use of "this"
  System.out.println("String & int args");
  }
  Flower() {
  this("hi", 47);
  System.out.println(
  "default constructor (no args)");
  }
  void print() {
//! this(11); // Not inside non-constructor!
  System.out.println(
  "petalCount = " + petalCount + " s = "+ s);
  }
  public static void main(String[] args) {
  Flower x = new Flower();
  x.print();
  }




为什么此构造函数不调用下面的构造函数? 请高手多多指点!
 Flower(String ss) {
  System.out.println(
  "Constructor w/ String arg only, s=" + ss);
  s = ss;
  }

------解决方案--------------------
this(petals); 
//! this(s); // Can 't call two! 
把这里改成
// this(petals); 
this(s); // Can 't call two! 
这样就调用了。
调用不调用,取决于你在构造实例时有没有调用相应的构造方法。

------解决方案--------------------
public static void main(String[] args) { 
Flower x = new Flower(); 
x.print(); 

按照你写的,程序会调用Flower(){。。。}这个构造函数
要想调用Flower(String ss)你应该这样写
public static void main(String[] args) { 

Flower x = new Flower("someString"); 
x.print(); 


------解决方案--------------------
这是一个调用方法的问题啊
问题在于this(s)与this.s这两种调用方法的不同。this(s)就会调用类方法Flower(String ss)进行赋值,但是this.s则是直接对Flower的S成员进行赋值,所以不调用类方法Flower(String ss)。
如果你把程序改成
 this(s); 
 this.petalCount = petals;
那么你将会看到类方法 Flower(String ss)被调用了但是 Flower(int petals) 不被调用。
------解决方案--------------------
对于2楼的问题,按LZ的程序来说,调用次序是Flower() 、Flower(String s, int petals) 、Flower(int petals) 、 void print()