Java - 访问不同类中的子类构造函数
问题描述:
我想实例化一个对象(在“Ship”类的“EmptySea”子类中创建)到另一个“海洋”类中以用“EmptySea”对象填充数组。Java - 访问不同类中的子类构造函数
错误是“EmptySea无法解析为某种类型”。
这里是我的海洋类代码:
public class Ocean {
// Instance variables.
public Ship[][] ships = new Ship[10][10];
public int shotsFired;
public int hitCount;
// Constructor.
public Ocean() {
shotsFired = 0;
hitCount = 0;
for (int row = 0; row < ships.length; row++) {
for (int column = 0; column < ships[row].length; column++) {
ships[row][column] = new EmptySea();
public abstract class Ship {
// Instance variables.
private int bowRow;
private int bowColumn;
private int length;
private boolean horizontal;
private boolean[] hit = new boolean[4];
// No constructor needed for Ship class.
// Methods (too many to show).
public class EmptySea extends Ship {
// Constructor.
EmptySea() {
length = 1;
}
// Inherited methods to define.
int getLength() {
return length = 1;
}
String getShipType() {
return "Empty";
}
@Override
boolean shootAt(int row, int column) {
return false;
}
@Override
boolean isSunk() {
return false;
}
@Override
public String toString() {
return "-";
}
}
的船舶阵列已经正确声明为海洋类的一个实例变量。基本上,它不让我把EmptySea()对象(“Ship”类和它的“EmptySea”子类的代码正确运行)。
在这种情况下,我需要以某种方式引用超类吗?
如果有一个更简单的方法来做到这一点,我不能这样做(这种方式是在作业中指定的)。
答
了解有关static nested class
and an instance nested class
之间的区别。
其他一些SO question就一样。
短期:静态声明你的内心EmptySea
类,然后读/理解为什么 - 简单地说,没有static
的EmptySea实例不能一Ship
实例的上下文之外创建。
评论是不适合扩展讨论;这个对话已经[转移到聊天](http://chat.*.com/rooms/130016/discussion-on-question-by-broncosaurus-java-accessing-a-subclass-constructor-i)。 –