Java 实例变量在两条语句中声明和初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3694197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:02:11  来源:igfitidea点击:

Java instance variable declare and Initialize in two statements

javavariablesinitializationinstance

提问by ddfnfal

Hi I'm having problem with initialization in java, following code give me compile error called : expected instanceInt = 100; but already I have declared it. If these things relate with stack and heap stuff please explain with simple terms and I'm newbie to java and I have no advanced knowledge on those area

嗨,我在 java 中的初始化有问题,下面的代码给了我一个名为:expected instanceInt = 100; 的编译错误。但我已经宣布了。如果这些东西与堆栈和堆有关,请用简单的术语解释,我是 Java 新手,我对这些领域没有高级知识



public class Init { 

int instanceInt;  
instanceInt = 100;

   public static void main(String[] args) {

     int localInt;
     u = 9000;
     }

}  

回答by Colin Hebert

You can't use statements in the middle of your class. It have to be either in a block or in the same line as your declaration.

你不能在课堂中间使用语句。它必须在一个块中或与您的声明在同一行中。



The usual ways to do what you want are those :

做你想做的事情的通常方法是:

  • The initialization during the declaration

    public class MyClass{
        private int i = 0;
    }
    

    Usually it's a good idea if you want to define the default value for your field.

  • The initialization in the constructor block

    public class MyClass{
        private int i;
        public MyClass(){
            this.i = 0;
        }
    }
    

    This block can be used if you want to have some logic (if/loops) during the initialization of your field. The problem with it is that either your constructors will call one each other, or they'll all have basically the same content.
    In your case I think this is the best way to go.

  • The initialization in a method block

    public class MyClass{
        private int i;
        public void setI(int i){
            this.i = i;
        }
    }
    

    It's not really an initialization but you can set your value whenever you want.

  • The initialization in an instance initializer block

    public class MyClass{
        private int i;
        {
             i = 0;
        }
    }
    

    This way is used when the constructor isn't enough (see comments on the constructor block) but usually developers tend to avoid this form.

  • 声明期间的初始化

    public class MyClass{
        private int i = 0;
    }
    

    如果您想为您的字段定义默认值,通常这是一个好主意。

  • 构造函数块中的初始化

    public class MyClass{
        private int i;
        public MyClass(){
            this.i = 0;
        }
    }
    

    如果您想在字段初始化期间有一些逻辑(if/loops),则可以使用此块。它的问题在于,要么您的构造函数相互调用,要么它们都具有基本相同的内容。
    在你的情况下,我认为这是最好的方法。

  • 方法块中的初始化

    public class MyClass{
        private int i;
        public void setI(int i){
            this.i = i;
        }
    }
    

    这不是真正的初始化,但您可以随时设置您的值。

  • 实例初始化块中的初始化

    public class MyClass{
        private int i;
        {
             i = 0;
        }
    }
    

    这种方式在构造函数不够用时使用(参见构造函数块的注释),但通常开发人员倾向于避免这种形式。



Resources :

资源 :

On the same topic :

在同一主题上:



Bonus :

奖金 :

What does this code ?

这段代码是什么?

public class MyClass {
    public MyClass() {
        System.out.println("1 - Constructor with no parameters");
    }

    {
        System.out.println("2 - Initializer block");
    }

    public MyClass(int i) {
        this();
        System.out.println("3 - Constructor with parameters");
    }

    static {
        System.out.println("4 - Static initalizer block");
    }

    public static void main(String... args) {
        System.out.println("5 - Main method");
        new MyClass(0);
    }
}

The answer

答案

回答by missingfaktor

Put it in an initializer block.

把它放在初始化块中。

public class Init { 

  int instanceInt;  
  {
    instanceInt = 100;
  }

  public static void main(String[] args) {
    int localInt;
    int u = 9000;
  }   
}  

Or simply initialize while declaring it:

或者在声明它时简单地初始化:

public class Init { 

  int instanceInt = 100;

  public static void main(String[] args) {
    int localInt;
    int u = 9000;
  }   
} 


References:

参考:

回答by fastcodejava

You need to do :

你需要做:

int instanceInt = 100;

If it was staticyou could initialize in a staticblock.

如果是,static你可以在一个static块中初始化。

回答by Shamim Hafiz

You can not have a separate statement to assign values to class members in the declaration area. You have to do this from a function, typically a class method.

您不能有单独的语句来为声明区域中的类成员赋值。您必须从函数(通常是类方法)中执行此操作。

For your case, consider doing the assignment as soon as you declare.

对于您的情况,请考虑在声明后立即进行分配。

回答by Michael Borgwardt

According to the Java Language Specification:

根据Java 语言规范

A class body may contain declarations of members of the class, that is, fields (§8.3), classes (§8.5), interfaces (§8.5) and methods (§8.4). A class body may also contain instance initializers (§8.6), static initializers (§8.7), and declarations of constructors (§8.8) for the class.

类主体可能包含类成员的声明,即字段(第 8.3 节)、类(第 8.5 节)、接口(第 8.5 节)和方法(第 8.4 节)。类主体还可以包含类的实例初始化器(第 8.6 节)、静态初始化器(第 8.7 节)和构造函数声明(第 8.8 节)。

However, the statement

然而,声明

instanceInt = 100;

is none of those things, therefore it is not allowed as part of a class body. What you need to do is this:

不是这些东西,因此它不允许作为类主体的一部分。你需要做的是:

int instanceInt = 100;

This is allowed because it is a field declarationthat includes a variable initializer.

这是允许的,因为它是一个包含变量初始值设定项的字段声明