2

我是 Java 新手并编写了简单的代码:

1 package Rndom;
2 class Clmm{
3   
4 }
5 public class Clkk {
6  
7   Clmm klm;
8   klm = new Clmm();
9
10 }

Eclipse 显示错误:

syntax error on token ";" , , expected on line 7

我试图找出显示此错误的原因。

4

4 回答 4

4

把这些线

 Clmm klm;
 klm = new Clmm();

在下面

公共静态无效主要例如

public static void main(String [] args)
{
 Clmm klm;
klm = new Clmm();
}
于 2012-07-29T15:51:19.000 回答
2

让它Clmm klm = new Clmm();

public class Clkk {

   private Clmm klm = new Clmm();

   // getter setter for klm
}

或在构造函数中实例化klm,如:

public class Clkk {

   private Clmm klm;
   public Clkk() {
       klm = new Clmm();
   }
   // getter setter for klm
}

或者你可以有块

public class Clkk {

   private Clmm klm;

   { // this is called block and this is equivalent to constructor. But you can not pass arguments to block. Prefer constructors.
       klm = new Clmm();
   }
   // getter setter for klm
}
于 2012-07-29T15:50:40.033 回答
2

您不能将语句放在类定义中的方法或构造函数之外:

klm = new Clmm();
于 2012-07-29T15:52:55.770 回答
1

您可以在减速期间在方法之外初始化变量。这就是为什么

private Clmm klm = new Clmm(); //deceleration and initialization

为你工作。但是,一旦它被声明(并初始化,即使它是默认值),您只能在方法或块内更改它的值。这就是为什么以下代码不适合您的原因:

Clmm klm; // deceleration and initialization to default value  
klm = new Clmm(); //assignment, which is a statement that cannot be outside of a block/method
于 2012-07-29T16:36:23.253 回答