Why can't I do assignment outside a method?

不问归期 提交于 2019-11-25 22:57:48

问题


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.


回答1:


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.

e.g.

class one{
 static final Integer b;

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



回答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




回答3:


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.




回答4:


This is the way java works, you cannot add non-declaration code (sorry i don't know the correct term) inside the class, that code should be inside methods.




回答5:


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.




回答6:


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.




回答7:


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.



来源:https://stackoverflow.com/questions/12062481/why-cant-i-do-assignment-outside-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!