繁体   English   中英

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

[英]How do I access an inner class constructor from a derived class?

对于以下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;
}

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

class Shark extends Ocean implements Behaviour {

    public Shark(int x, int y, int hungerLevel) {
        super(x,y);
    }
}

如何从Shark类构造函数访问Critter类构造函数?

似乎您应该扩展Critter而不是Ocean:

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

    }
...
}

为此,Criter必须是静态内部类。 我不知道您需要多少这种设计,但是内部类应限于彼此高度依赖的类,在这里情况并非如此。 如果可以,请将Critter移出海洋。

只要SharkOcean在同一包中,并且将static修饰符添加到Critter的类声明中,您就应该能够使用new Ocean.Critter()访问Critter

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM