简体   繁体   English

Java初学者:初始化类变量

[英]java beginner: initializing class variables

I've just read the SUN java code conventions ; 我刚刚阅读了SUN Java代码约定 very nice document btw. 顺便说一句非常不错的文件。 And I've read this 我已经读过了

6.3 Initialization: Try to initialize local variables where they're declared. 6.3初始化:尝试在声明了局部变量的地方初始化它们。 The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first. 不初始化声明变量的唯一原因是初始值是否取决于首先进行的某些计算。

And I was wondering if Class variables are having same suggestion or not, for example I have: 我想知道Class variables是否有相同的建议,例如,我有:

public class NNmatrix {

    protected ArrayList<ArrayList<Double>> matrix;     // line 1
    public NNmatrix() {
        matrix = new ArrayList<ArrayList<Double>>();     // line 2
    }
    /**
     * 
     * @param otherMtrx
     */
    public NNmatrix(final ArrayList<ArrayList<Double>> otherMtrx) {
        final int rows = otherMtrx.size();
        matrix = new ArrayList<ArrayList<Double>>(rows);  // line3
        for (int i = 0; i < rows; i++) {
            this.matrix.add(new ArrayList<Double>(otherMtrx.get(i)));
        }
    }
}

EDITING CODE# If I would initialize the variable where it's declared (in class), I would remove "line 2" and leave "line 3" because performance issue# reserving (rows) in memory as you know. 编辑代码#如果要在variable声明的位置(在类中)初始化variable ,则将删除 “第2行”并保留 “第3行”,因为您知道性能问题#保留(行)在内存中。

The question is: 问题是:

  1. Is doing that a good practice or initialization matter only apply for local variables inside methods etc only? 这样做是不是一种好的习惯或初始化问题,仅适用于方法等内部的局部变量?
  2. If it's fine, I want to know which will come first if I did the EDITING CODE# the initialization @ line 3 or initialization @ line 1 ? 如果可以的话,我想知道如果我在第3行的初始化或第1行的初始化中执行了EDITING CODE#,哪一个先出现?

These are instance variables, not class variables. 这些是实例变量,而不是类变量。 Instance variables belong to a specific object, class variables don't (sorry to nitpick). 实例变量属于特定对象,而类变量不属于(对nitpick很抱歉)。

I think initializing the variable where it's declared is simpler and easier to read. 我认为在声明该变量的位置初始化变量更容易阅读。

The jvm starts initializing instance variables and instance initializer blocks at the top of the file and works its way down, only after it has initialized all the variables and run the initializer blocks does it execute the constructor. 只有在初始化所有变量并运行初始化程序块之后,jvm才会开始在文件顶部初始化实例变量和实例初始化程序块,并向下进行下去。

The line you quoted refers only to local variables. 您引用的行仅指局部变量。 Because in Java local variables don't need to be declared at the top of the scope but can be declared anywhere before they are used, it makes a lot of sense. 因为在Java中,局部变量不需要在作用域的顶部声明,而是可以在使用它们之前在任何地方声明,所以这很有意义。

For class and instance variables, my personal preference is to initialize the variable where it is declared. 对于类和实例变量,我个人的喜好是在声明变量的地方对其进行初始化。 In many cases where I don't have any other constructors than the default this removes the need to have a default constructor written as the compiler will automatically provide one. 在许多情况下,除了默认构造函数外,我没有其他构造函数,因此无需编写默认构造函数,因为编译器会自动提供默认构造函数。 I find this cleans up and shortens my code. 我发现这可以清理并缩短代码。

In the second case constructor you provided you can make a good case for initializing in the constructor. 在第二种情况下,您提供的构造函数可以为在构造函数中进行初始化提供很好的条件。

With class variables I have found few times where I would want to initialize in the instantiation block instead of inline at the declaration. 使用类变量,我发现了几次我想在实例化块中进行初始化而不是在声明中进行内联的地方。

I would argue for leaving your code the way it is. 我会主张按原样保留您的代码。

While in general I do like to initialize instance variables at the declaration, I do not like to do so when I must re-initialize them in some constructor. 通常,我确实喜欢在声明中初始化实例变量,但是当我必须在某些构造函数中重新初始化实例变量时,我不喜欢这样做。 I prefer to either initialize at the declaration, or in every constructor-path (perhaps just in a single constructor called by every other constructor). 我更喜欢在声明处初始化,或者在每个构造函数路径中初始化(也许只是在每个其他构造函数调用的单个构造函数中)。 The pure declaration signals that something more complicated is going on, while moving the simplest initialization to the declaration can hide that. 纯声明表明发生了更复杂的事情,而将最简单的初始化移到声明可以将其隐藏。

You have a couple different options that probably all fall under micro-optimizations. 您有几个不同的选项,可能全部属于微优化。 Typically these types of optimizations are of little concern unless you are working with static variables in a concurrent environment or doing something funky like pooling classes. 通常,除非您在并发环境中使用静态变量或执行诸如池类之类的时髦操作,否则这些类型的优化几乎不需要关注。

  1. There's no reason why you cant initialize your variables in your constructor or other methods similar to what is outlined here . 没有理由不能在构造函数或其他类似于此处概述的方法中初始化变量。 Personally, I prefer to initialize my variables at their declaration whenever possible. 就个人而言,我更愿意在可能的时候在变量的声明中初始化我的变量。

  2. From my understanding, initialization will occur at roughly the same time if occurring in the constructor vs at declaration. 据我了解,如果在构造函数中进行初始化,而在声明中进行初始化,则初始化几乎同时发生。 I've never had to know which actually comes first in practice, but you could do a simple System.out test to find out. 我从不需要知道实际上哪个是最先出现的,但是您可以执行一个简单的System.out测试来找出答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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