Java实例变量在两个语句中声明和初始化 [英] Java instance variable declare and Initialize in two statements

查看:119
本文介绍了Java实例变量在两个语句中声明和初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

public class Init { 

int instanceInt;  
instanceInt = 100;

   public static void main(String[] args) {

     int localInt;
     u = 9000;
     }

}  


推荐答案

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

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 :


  • 声明期间的初始化

public class MyClass{
    private int i = 0;
}

通常情况下,如果要为字段定义默认值,这是一个好主意。

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

构造函数块中的初始化

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

如果您想拥有一些,可以使用此块在字段初始化期间的逻辑(if / loops)。它的问题是你的构造函数会相互调用一个,或者它们都具有基本相同的内容。

在你的情况下,我认为这是最好的方法。

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.

方法块中的初始化

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.

实例初始化程序块中的初始化

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.

资源:

  • JLS - Instance Initializers

关于同一主题:

  • Use of Initializers vs Constructors in Java
  • How is an instance initializer different from a constructor?

奖金:

这段代码是什么?

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

这篇关于Java实例变量在两个语句中声明和初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆