【问题标题】:Really simple java syntax clarification真正简单的java语法说明
【发布时间】:2015-03-16 18:44:23
【问题描述】:

我从来没有学过Java,但我需要理解下面这段代码的含义,主要问题是花括号:

/**
 *   This Universe uses the full HashLife algorithm.
 *   Since this algorithm takes large steps, we have to
 *   change how we increment the generation counter, as
 *   well as how we construct the root object.
 */
public class HashLifeTreeUniverse extends TreeUniverse {
   public void runStep() {
      while (root.level < 3 ||
             root.nw.population != root.nw.se.se.population ||
             root.ne.population != root.ne.sw.sw.population ||
             root.sw.population != root.sw.ne.ne.population ||
             root.se.population != root.se.nw.nw.population)
         root = root.expandUniverse() ;
      double stepSize = Math.pow(2.0, root.level-2) ;
      System.out.println("Taking a step of " + nf.format(stepSize)) ;
      root = root.nextGeneration() ;
      generationCount += stepSize ;
   }
   {
      root = HashLifeTreeNode.create() ;
   }
}

特别是在列表底部的这个声明:

   {
      root = HashLifeTreeNode.create() ;
   }

貌似没有签名的方法,是什么意思?

提前谢谢你!

【问题讨论】:

标签: java


【解决方案1】:

那是instance initializer

这是在构造函数主体执行之前作为构造新实例的一部分执行的代码。不过,直接在一个方法之后以这种方式布局它是很奇怪的。 (说实话,这种情况比较少见。在这种情况下,如果该字段在同一个类中声明,它看起来应该只是一个字段初始化程序。(不清楚您是否向我们展示了 全班与否。)

实例初始化程序和字段初始化程序按文本顺序执行,在超类构造函数之后,“this”构造函数体之前。

例如,考虑以下代码:

class Superclass {
    Superclass() {
        System.out.println("Superclass ctor");
    }
}

class Subclass extends Superclass {
    private String x = log("x initializer");

    {
        System.out.println("instance initializer");
    }

    private String y = log("y initializer");

    Subclass() {
        System.out.println("Subclass ctor");
    }

    private static String log(String message)
    {
        System.out.println(message);
        return message;
    }
}

public class Test {    
    public static void main(String[] args) throws Exception {
        Subclass x = new Subclass();
    }
}

输出是:

Superclass ctor
x initializer
instance initializer
y initializer
Subclass ctor

【讨论】:

  • 这真的是我看到的 2005 年的旧代码,取自:drdobbs.com/jvm/an-algorithm-for-compressing-space-and-t/… 谢谢
  • 这个根可能是扩展基类的受保护根吗?如果是这样:非常不喜欢!
  • @laune:是的,我怀疑这是对的,我也不喜欢它。
  • 知道了,不喜欢... :) 谢谢 :)
【解决方案2】:

它是一个instance block(几段代码),在构建实例之前执行,每次您尝试创建 HashLifeTreeUniverse 实例时都会执行该实例。

您突出显示的大括号之间的代码将在调用构造函数之前执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多