Question

My question is regarding the declaration and value assignment rules in Java. When writing the fields we can declare and assign values together but we cannot do the same separately.

E.G.:

class TestClass1 {
    private int a = 1;
    private int b ;
     b= 1;
    private int sum;

    public int getA() {
        return a;
    }

    public int getB() {
        return b;
    }

    public int getSum() {
        sum = a + b;
        return sum;
    }

}

public class TestClass {
    public static void main(String[] args) {
        TestClass1 testClass1 = new TestClass1();

        System.out.println("total =" + testClass1.getSum());
    }    

}    

Here in line:

private int a = 1; 

We are able to declare a as a private int and assign a value 1 to it. But in case of:

private int b ;
b= 1; 

Eclipse does not allow this to happen and throws an error. Kindly explain the logic behind this.

Était-ce utile?

La solution

Code inside a class, but outside a function, is purely declarations. It does not get "executed". It simply declares what fields a class contains.

The reason you can do the shorthand private int a = 1; is just syntactic sugar that the Java language allows. In reality, what happens is that the a = 1 part is executed as part of the constructor. It's just easier to read and write when it is next to the variable declaration.

It's something nice that the Java langage creators allowed. Not every language allows that, look at C++ as an example that does not always allow it.

Autres conseils

you have to put b=1; inside a method or put this inside a constructor.

you are getting this error since you can't do any thing other than declaration(private int a= 1; ) in class level.

It's just a question of syntax in Java. In the example you show, you try to affect a value to b in the member declaration part of your class. This is not allowed by the syntax of Java. You can only do it when you declare your attribute, in the body of a method or in a static block if your attribute is static e.g. :

private static int b;
static {
    b = 1;
}

It is only a syntax problem. You can do it like this :

private int b ;

{  // <- Initialization block
  b= 1;
}

See What is an initialization block?

You are unable to write logic directly in the class. You should move it to the constructor.

Java only allow declaration within the class and outside any method. Declarations like int b = 1; will be executed when you initialize a new Object.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top