我是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
我试图找出显示此错误的原因。
答案 0 :(得分:4)
把这些行
Clmm klm;
klm = new Clmm();
下的
public static void main。例如
public static void main(String [] args)
{
Clmm klm;
klm = new Clmm();
}
答案 1 :(得分: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
}
答案 2 :(得分:2)
您不能在类定义中将语句放在方法或构造函数之外:
klm = new Clmm();
答案 3 :(得分: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