如何从派生类访问内部类构造函数?

ove*_*nge 0 java constructor

对于以下Ocean课程,

public class Ocean {

    /**
     * Define any variables associated with an Ocean object here. These
     * variables MUST be private.
     */
    // width of an Ocean
    private final int width;
    // height of an Ocean
    private final int height;

    class Critter {

        /**
         * Defines a location of a Critter in an Ocean.
         */
        Point location;

        public Critter(int x, int y) {
            location = new Point(x,y);
        }

        public Point getLocation() {
            return location;
        }
    }

    private Critter[][] oceanMatrix;
}
Run Code Online (Sandbox Code Playgroud)

我想Critter从下面的类Shark构造函数访问上面的类中的构造函数.

class Shark extends Ocean implements Behaviour {

    public Shark(int x, int y, int hungerLevel) {
        super(x,y);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何CritterShark类构造函数中访问类构造函数?

Oza*_*zan 6

看起来你应该延伸Critter而不是海洋:

class Shark extends Ocean.Critter implements Behaviour{
...
    public Shark(int x, int y, int hungerLevel){
        super(x,y);

    }
...
}
Run Code Online (Sandbox Code Playgroud)

为了实现这一点,Critter需要成为一个静态的内部类.我不知道这个设计有多少是你的,但是内部类应该限于彼此强烈依赖的类,这不是这里的情况.如果可以的话,把Critter带出海洋.

  • 如果需要,如果Critter是一个非静态内部类,使用一个名为[qualified superclass constructor invocation]的模糊语法(http://docs.oracle.com/javase/specs/jls/se8/html),就可以使它工作. /jls-8.html#d5e14226).例如,`class Shark扩展Ocean.Critter {Shark(Ocean ocean,int x,int y){ocean.super(x,y); }. (2认同)