全局变量(或者属性)的初始化问题

总结:定义的全局变量(即类的属性)——数组、基本数据类型、其他引用类型变量,

  • 采用静态初始化方式,即定义变量的同时进行初始化;
  • 采用动态初始化方式,只在属性处定义变量,初始化放在方法中进行;
  • 错误操作:先定义属性中的变量,接着换行再进行初始化。(详细见下)

1.定义变量的时候,立刻初始化,即静态初始化;

public class Test {
    int a = 1;//静态初始化基本数据类型

    String[] s = {"Hello","World","你好,世界"};//静态初始化引用类型数组
    Example[] e = {new Example(2019,"小明"),new Example(2018,"小红")};

}
class Example{
    int id;
    String name;

    public Example(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

2.只定义,最后在方法中进行初始化;

public class Test02 {
    int a;
    String[] s;
    Example[] e = new Example[2];
    public void se(){
        a = 1;//动态初始化,必须在方法中,进行
        e[0] = new Example(2019,"小明");//同理,数组的动态初始化也必须在方法中进行,静态方法或者动态方法均可
        e[1] = new Example(2018,"小红")
    }
}
class Example{
    int id;
    String name;

    public Example(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

3、错误初始化操作(如下代码报错)

public class Test03 {
    int a;
    a = 1;//直接对全局变量(即属性),先定义,接着初始化,这是错误的
    String[] s;
    s = {"ab","cd","ef"};
    Example[] e = new Example[2];
    e[0] = new Example(2019,"小明");//同理,数组也不能这样初始化操作
    e[1] = new Example(2018,"小红");
}
class Example{
    int id;
    String name;

    public Example(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

猜你喜欢

转载自www.cnblogs.com/pxb2018/p/10532865.html
今日推荐