[英]Java - Accessing a subclass constructor in a different class
我試圖將一個對象(在“ Ship”類的“ EmptySea”子類中創建)實例化為另一個“ Ocean”類,以用“ EmptySea”對象填充數組。
錯誤為“ 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 "-";
}
}
在Ocean類中,ships數組已正確聲明為實例變量。 基本上,這不是讓我放置EmptySea()對象(“ Ship”類及其“ EmptySea”子類的代碼正確運行)。
在這種情況下,我需要以某種方式引用超類嗎?
如果有一種更簡單的方法,我就不能那樣做(這種方式在作業中指定)。
了解static nested class
和instance nested class
之間的區別。
其他一些同樣的問題 。
短期:使用靜態聲明內部的EmptySea
類,然后閱讀/理解原因-簡而言之,沒有static
的EmptySea實例不能在Ship
實例的上下文之外創建。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.