public class Flower {
  private int petalCount = 0;
  private String s = new String("null");
  Flower(int petals) {
    petalCount = petals;
    System.out.println(
      "Constructor w/ int arg only, petalCount= "
      + petalCount);
  }
  Flower(String ss) {
    System.out.println(
      "Constructor w/ String arg only, s=" + ss);
    s = ss;
  }
  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();
  }
}
我有几点不太明白.代码里的S在流程里的内容是"hi"而一些构造函数里的this.s怎么就会是null了?希望高手能帮我分析一下this("hi", 47)和Flower(String s, int petals)会产生什么样的影响?还有就是private String s = new String("null");又改变了什么?谢谢!

解决方案 »

  1.   

    你好,,我顺序清楚了..就是不清楚this.s和s是指的同一个变量?
      

  2.   

    顺序清楚了这就没什么问题了吧,this.s是类中 的变量  或者说是类的属性  s是传个Flower方法的一个参数  他们没任何关系  不过就是在这个构造方法中把属性s指向了传过来的s
      

  3.   

    private String s = new String("null");又改变了什么?谢谢!这个就是初始化 你看看string类就知道了 多看api有好处地:)
      

  4.   

    This 返回的是当前对象的引用。在这里也就是当前类的引用。同时他又能调用当前类的构造方法。由于他是实例对象,所以不能出现在静态(类)方法中!!