如何从静态嵌套类修改外部类字段?

J.O*_*sen 0 java oop

修改外类字段的正确方法是什么?当尝试从内部静态类更改时value,Artifact它会产生错误.需要迭代包含类型对象的数组列表Artifact; 并且能够为每个Artifact(无论是硬币还是高脚杯)显示该值.

 public class Artifact {
        public int value = 0;

        public static class  Goblet extends Artifact{
            value = 5; // Syntax error on token "value", VariableDeclaratorId expected after this token
        }
        public static class Coin extends Artifact{
            value = 10;
        }

    }
Run Code Online (Sandbox Code Playgroud)

ass*_*ias 5

您不能value = xxx;在方法或块之外使用语句.

这可行:

public class Artifact {

    public static void main(String[] args) {
        Artifact goblet = new Goblet();
        Artifact coin = new Coin();

        System.out.println(goblet.value); //prints 5
        System.out.println(coin.value); //prints 10
    }

    public int value = 0;

    public static class Goblet extends Artifact {

        {value  = 5;}
    }

    public static class Coin extends Artifact {

        {value  = 10;}
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它是一个实例初始化块. (2认同)