Reputation: 187
I am being beginner trying to learn java basics and here in the this program I am confused why
we can't reassign the value of class instance variable.
this is error in this program. Please guys help me out to figure it out. thanks
class AddInsideClassVar{
int a = 3;
int c;
c = a + a;
public static void main(String args[]){
System.out.println();
}
}
Upvotes: 1
Views: 365
Reputation: 8254
Explanation : int c = a + a is a declaration whereas " c = a + a ; " ( alone ) is a statement ; You have a point, it does not make much sense ;
class MyClass {
int a = 3;
int c = a + a; // Correct
}
or
class MyClass {
int a = 3;
int c;
public void addition () {
c = a + a; // Correct
}
}
but not
class MyClass {
int a = 3;
int c;
c = a + a; // Incorrect
}
NOTE : On the other, the Scala programming language ( compiles to JVM ) allows you to do the following :
scala> class MyClass { val a:Int = 3;
var c:Int = _;
c = a + a ; // Correct
}
defined class MyClass
Upvotes: 0
Reputation: 4863
You may define fields within a class, but you are not allowed to put calculation statements outside of a method definition. A field declaration is of the form type; or type = value;
For example (from your code);
class AddInsideClassVar{
static int a = 3; // ok this is a declaration for a field (variable)
static int c; // ok, this is too
//c = a + a; // this is a statement and not a declaration. A field may be
// declared only once
static int d = a + a; // this will work since it is part of a declaration.
public static void main(String args[]){
System.out.println("a=" + a + ", c=" + c + ", d=" + d);
}
}
Upvotes: 2
Reputation: 3856
You may be mixing your statics with instance variables. Here's how I would write this to not confuse myself:
public class AddInsideClassVar{
int a;
int c;
public void doStuff() {
a = 3;
c = a + a;
}
public static void main(String args[]){
AddInsideClassVar instance = new AddInsideClassVar();
instance.doStuff();
System.out.println(c);
}
}
a and c are instance variables. They are manipulated by a non-static method which requires an instance of the class to operate on. So, I create the instance in main(), then call the function to manipulate instance variables.
Upvotes: 0
Reputation: 7784
You can try this (just an example of workaround):
class AddInsideClassVar{
static {
int a = 3;
int c;
c = a + a;
System.out.println(c);
}
public static void main(String args[]){
}
}
Upvotes: 1
Reputation:
You cannot execute c = a + a in that section. If anything you'd need to do
int a = 3;
int c = a + a;
If you make these variables static then you could do
private static int a = 3;
private static int c;
static {
c = a + a;
}
Upvotes: 1