0

我有这样的代码:

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 的封闭实例这是什么意思,我应该如何重构我的代码才能工作?

4

1 回答 1

1

您需要将SwarmEnemy1SwarmEnemy2移到SwarmEnemy类之外。

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);
        }
    }
}
于 2013-02-13T18:46:40.680 回答