Reputation: 4718
I am new to Java and written simple code:
1 package Rndom;
2 class Clmm{
3
4 }
5 public class Clkk {
6
7 Clmm klm;
8 klm = new Clmm();
9
10 }
Eclipse shows the error:
syntax error on token ";" , , expected on line 7
I am trying to find why this error is displayed.
Upvotes: 2
Views: 182
Reputation: 66
You can initialize a variable outside of a method, during it's deceleration. That's why
private Clmm klm = new Clmm(); //deceleration and initialization
Worked for you. However, once it's declared (and initialized, even if it's to a default value) you can only change it's value inside a method or a block. That's why the following code did not work for you:
Clmm klm; // deceleration and initialization to default value
klm = new Clmm(); //assignment, which is a statement that cannot be outside of a block/method
Upvotes: 1
Reputation: 16158
Make it Clmm klm = new Clmm();
like
public class Clkk {
private Clmm klm = new Clmm();
// getter setter for klm
}
Or instantiate klm
in constructor like :
public class Clkk {
private Clmm klm;
public Clkk() {
klm = new Clmm();
}
// getter setter for klm
}
OR you can have block as
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
}
Upvotes: 2
Reputation: 159754
You cannot put statements outside methods or constructors in the class definition:
klm = new Clmm();
Upvotes: 2
Reputation: 8881
put these lines
Clmm klm;
klm = new Clmm();
under
public static void main e.g.
public static void main(String [] args)
{
Clmm klm;
klm = new Clmm();
}
Upvotes: 4