[英]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移出海洋。
只要Shark
与Ocean
在同一包中,并且将static
修饰符添加到Critter
的类声明中,您就应该能够使用new Ocean.Critter()
访问Critter
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.