首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

java构造函数有关问题

2012-01-07 
java构造函数问题public class Flower {private int petalCount 0private String s new String(null

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()

热点排行