简体   繁体   中英

Why can't I do assignment outside a method?

If I try to assign a value to a variable in a class, but outside a method I get an error.

class one{
 Integer b;
 b=Integer.valueOf(2);
}

but, if I initialize it during the creation, it works.

class one{
 Integer b=Integer.valueOf(2);
}

Inside a method, it works in both cases.

you need to do

class one{
 Integer b;
 {
    b=Integer.valueOf(2);
 }
}

as statements have to appear in a block of code.

In this case, the block is an initailiser block which is added to every constructor (or the default constructor in this case) It is run after any call to super() and before the main block of code in any constructor.

BTW: You can have a static initialiser block with static { } which is called when the class is initialised.

eg

class one{
 static final Integer b;

 static {
    b=Integer.valueOf(2);
 }
}

Because the assignments are statements and statements are allowed only inside blocks of code(methods, constructors, static initializers, etc.)

Outside of these only declarations are allowed.

This :

  class one{
        Integer b=Integer.valueOf(2);
  }

is a declaration with an initializer. That's why is accepted

A more general answer would be that the class body is about declarations , not statements . There is special provision for statements occuring in class body, but they have to be marked explicitly as either class initializers or instance initializers .

In Java, when defining a class, you can define variables with default values and add methods. Any executable code (such as assignments) MUST be contained in a method.

这是java的工作方式,你不能在类中添加非声明代码(对不起,我不知道正确的术语),该代码应该在方法中。

I think terminology-wise, couple of other answers are slightly off. Declarations are also statements. In fact, they are called "declaration statements", which are one of the three kinds of statements. An assignment statement is one form of "expression statement" and can be used only in constructs such as methods, constructors, and initializers. Check out the Statements section in this Oracle's tutorial link .

Methods have the responsibility to perform mutations on the member variables. If the member variable needs to be initialized, java provides a way to do it during construction, class definition (latter case). But the mutation cannot be performed during definition.(former case). It is usually done at the method level.

Objects are meant to hold the state, while methods are meant to operate on that state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM