This is my code:
public class MyClass {
int x;
MyClass m1 = new MyClass();
m1.x=10;
}
Why does line m1.x=10; result in error?
This is my code:
public class MyClass {
int x;
MyClass m1 = new MyClass();
m1.x=10;
}
Why does line m1.x=10; result in error?
Use instance initialization block:
public class MyClass {
int x; // define x variable
MyClass m1 = new MyClass(); // initialize m1 variable
{
m1.x=10; // assign 10 to m1.x (this is assignment statement)
}
}
Out of block you can do only defining and initializing variables, not assignment statement.
There are two errors in your code:
MyClass m1 = new MyClass();
This is an infinite recursion.
m1.x=10;
This is a statement, and as such should be within a method or constructor, not the class body.
Exception in thread "main" java.lang.StackOverflowError to be desirable behaviorpublic class Test { Test test = new Test(); public static void main(String[] args) { new Test(); } } The problem here is the code m1.x=10;
This line shows an operation or behavior which is only permissible within a block of code.
Valid Code for this operation.
public class MyClass {
int x;
public void assignOperation() {
this.x = 10;
}
public static void main( String[] args ) {
MyClass myClass = new MyClass();
myClass.assignOperation();
System.out.println( "Assigned value is " + this.x )
}
}
Another valid example outside of a method but within the class body will be :
public class MyClass {
static int x;
static {
x = 10;
}
public static void main( String[] args ) {
System.out.println( "Assigned value is " + x )
}
}
making variable x static doesn't need us initialize an object of the class MyClass.