Why does Eclipse require me to set (arbitrary) brackets in java code?

后端 未结 5 1202
-上瘾入骨i
-上瘾入骨i 2021-01-29 11:56

I am currently trying to figure out how to use Eclipse to program Escape models in java. I am quite new to Escape and Eclipse, and it has been a while since I programmed in java

5条回答
  •  日久生厌
    2021-01-29 12:10

    If you separate field initialization from declaration, you need a method or an initializer. This instance works without initializers:

    package ede.brook.model;
    
    import org.ascape.model.Scape;
    
    public class CoordinationGame extends Scape {
    
        public int latticeHeight = 30;
        public int latticeWitdh = 30;
        public int nPlayers = 200;
    
        Scape lattice  = new Scape(new Array2DVonNeumann());;
        Scape players;
    
        boolean test = true;
        int test2 = 3;
    
        test = true;
        test2 = 3;
    
    }
    

    If an initializer is present, they are executed before the constructors.

    As for coding practice, I would recommend against initializers and use a combined declaration + initialization for simple cases or (parameterless) constructors for more complicated constructs. An exception are static initializers, which may be necessary for more complex initializations:

    static SomeTypeWithComplexInitialization staticField;
    
    static {
      SomeOtherType factoryParameter = new SomeOtherType()
      staticField = SomeTypeFactory.createInstance(factoryParameter);
    }
    

    The only other instance where I would recommend using initializers are APIs that specifically recommend this. For example, JMock uses this syntax to provide an easy-to-grock lambda-like construct:

    context.checking(new Expectations() {{
        oneOf (subscriber).receive(message);
    }});
    

提交回复
热议问题