Mytest.java的代码如下:
class WaterSource {
  private String s;
  WaterSource() {
    System.out.println("WaterSource()");
    s = new String("Constructed");
  }
  public String toString() { return s; }
}public class Mytest{
WaterSource source ;
source = new WaterSource();
  void print() {
    System.out.println("source = "  + source.toString()); 
  }
public static void main(String args[]){
Mytest x = new Mytest();
    x.print();
}
}
先声明一个对象, 再实例化出错, 错误提示:
Mytest.java:12: <identifier> expected
source = new WaterSource();
               ^
1 error。
如果把  
WaterSource source ;
source = new WaterSource();改成:   WaterSource = new WaterSource();  
后, 程序就能正常编译通过!  这是为什么呢?

解决方案 »

  1.   

    source = new WaterSource();需要在方法中完成
      

  2.   

    class WaterSource {
      private String s;
      WaterSource() {
        System.out.println("WaterSource()");
        s = new String("Constructed");
      }
      public String toString() { return s; }
    }public class Mytest{
    //WaterSource source ;
    WaterSource source = new WaterSource();
      void print() {
        System.out.println("source = "  + source.toString()); 
      }
    public static void main(String args[]){
    Mytest x = new Mytest();
        x.print();
    }
    }
    这样改一下就可以了
      

  3.   

    -----------------
    WaterSource source ;//定义
    source = new WaterSource();//这句被认为为赋值语句
    赋值语句应该放在方法里
    -----------------------
    WaterSource = new WaterSource(); //定义
      

  4.   

    这么写 string 变量不好哦~~
    s = new String("Constructed");
      

  5.   


    public class Mytest中public 去掉也可以的