Reputation: 27
In a normal class,
public class MyClass {
int a =12;
}
works fine.
But,
public class MyClass {
int a =12;
int b;
b=13;
}
this gives a compilation error.
I know I am trying to access a field without using an object of that class, so I even tried this->
public class MyClass {
int a =12;
int b;
MyClass m= new MyClass();
m.b=13;
}
but even this doesn't seem to work.
I can accept the fact that this is how things work and move on. But does anyone know the logic behind this?
Thank you in advance.
Upvotes: 0
Views: 1126
Reputation: 623
int a = 12;
This is a variable declaration with initialisation.
b=13;
This is an assignment; a statement; it cannot be part of the declaration. It has to be part of the constructor or method.
It is how Java object definition works.
Upvotes: 1
Reputation: 79055
You can do it in one of the following two ways:
Use the initialization block as follows:
int b;
{
b = 13;
}
Do the following in the constructor:
b = 13;
Check https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html to learn more about it.
Upvotes: 0