包含Swarm.SwarmEnemy.SwarmEnemy1的封闭实例是必需的

时间:2013-02-13 17:40:40

标签: java

我有这样的代码:

public class Swarm {

    public SwarmEnemy getEnemy() {
        return new SwarmEnemy.SwarmEnemy1(SwarmEnemy.NORMAL_SWARM); // <-ERROR
    }

    private class SwarmEnemy extends BeamEnemy {

        public static final int NORMAL_SWARM = 0;

        public SwarmEnemy(int hp, int swarmType) {
            super(0, 0, hp, 0);
            switch (swarmType) {
                case 0:
                    System.out.println("constructor 1");
                    break;
            }
        }

        private class SwarmEnemy1 extends SwarmEnemy {

            public SwarmEnemy1(int swarmType) {
                super(25, swarmType);
            }
        }

        private class SwarmEnemy2 extends SwarmEnemy {

            public SwarmEnemy2(int swarmType) {
                super(25, swarmType);
            }
        }

    }
}

我试图制作工厂装饰器。无论如何 - 这是我得到的错误:包含Swarm.SwarmEnemy.SwarmEnemy1的封闭实例是必需的它是什么意思,我应该如何重构我的代码?

1 个答案:

答案 0 :(得分:1)

您需要在 SwarmEnemy 类之外移动 SwarmEnemy1 SwarmEnemy2

public class Swarm {

    public SwarmEnemy getEnemy() {
        return new SwarmEnemy1(SwarmEnemy.NORMAL_SWARM); // <-ERROR
    }

    private class SwarmEnemy extends BeamEnemy {

        public static final int NORMAL_SWARM = 0;

        public SwarmEnemy(int hp, int swarmType) {
            super(0, 0, hp, 0);
            switch (swarmType) {
                case 0:
                    System.out.println("constructor 1");
                    break;
            }
        }
    }

    private class SwarmEnemy1 extends SwarmEnemy {

        public SwarmEnemy1(int swarmType) {
            super(25, swarmType);
        }
    }

    private class SwarmEnemy2 extends SwarmEnemy {

        public SwarmEnemy2(int swarmType) {
            super(25, swarmType);
        }
    }
}