Java - 在不同的 class 中访问子class 构造函数
Java - Accessing a subclass constructor in a different class
我正在尝试将一个对象(在 "Ship" class 的 "EmptySea" 子 class 中创建)实例化为另一个 "Ocean" class 用 "EmptySea" 个对象填充数组。
错误是"EmptySea cannot be resolved to a type."
这是我的海洋class代码:
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 "-";
}
}
ships 数组已正确声明为 Ocean 中的实例变量 class。基本上,它不允许我放置 EmptySea() 对象("Ship" class 及其 "EmptySea" subclass 的代码正确运行)。
在这种情况下我需要以某种方式引用 superclass 吗?
如果有更简单的方法,我不能那样做(这种方法在作业中指定)。
了解 static nested class
and an instance nested class
.
之间的区别
其他一些 SO question 相同。
短期:用静态声明你的内部 EmptySea
class,然后 read/understand 为什么 - 简而言之,没有 static
不能在上下文之外创建 EmptySea 实例Ship
个实例。
我正在尝试将一个对象(在 "Ship" class 的 "EmptySea" 子 class 中创建)实例化为另一个 "Ocean" class 用 "EmptySea" 个对象填充数组。
错误是"EmptySea cannot be resolved to a type."
这是我的海洋class代码:
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 "-";
}
}
ships 数组已正确声明为 Ocean 中的实例变量 class。基本上,它不允许我放置 EmptySea() 对象("Ship" class 及其 "EmptySea" subclass 的代码正确运行)。
在这种情况下我需要以某种方式引用 superclass 吗?
如果有更简单的方法,我不能那样做(这种方法在作业中指定)。
了解 static nested class
and an instance nested class
.
其他一些 SO question 相同。
短期:用静态声明你的内部 EmptySea
class,然后 read/understand 为什么 - 简而言之,没有 static
不能在上下文之外创建 EmptySea 实例Ship
个实例。