[英]Java - Class that extends a class, and has a component that extends the other class' component
[英]Java - extends seems to be calling constructor of other class
我正在嘗試java,我似乎遇到了一些問題。 我似乎唯一的問題是當我添加Stars類的擴展時,構造函數似乎被調用而沒有我聲明像Stars test = new Star();
Knight.java
import javax.swing.JOptionPane;
public class Knight extends Stars {
private String name;
private int health, battles, age, gold;
public Knight() {
name = JOptionPane.showInputDialog("What is the knight's name?");
String message = String.format("How much health does %s have?", name);
health = Integer.parseInt(JOptionPane.showInputDialog(message));
message = String.format("How many battles has %s been in?", name);
battles = Integer.parseInt(JOptionPane.showInputDialog(message));
message = String.format("How old is %s?", name);
age = Integer.parseInt(JOptionPane.showInputDialog(message));
message = String.format("How much gold does %s have?", name);
gold = Integer.parseInt(JOptionPane.showInputDialog(message));
}
public String getStats() {
// String message =
return String.format("\nKnight Name: %s\nKnight Health: %d\nKnight Battles: %d\nKnight Age: %d\nKnight Gold: $%d\n\n", name, health, battles, age, gold);
}
}
Stars.java導入javax.swing.JOptionPane;
public class Stars {
private int rows, cols;
private String skyScape = new String();
public Stars() {
rows = Integer.parseInt(JOptionPane.showInputDialog("How many rows of stars are there?"));
cols = Integer.parseInt(JOptionPane.showInputDialog("How many columns of stars are there?"));
for (int count = 0; count < rows; ++count) {
if ((count % 2) == 1) {
skyScape += " *";
} else {
skyScape += "*";
}
for (int colCount = 1; colCount < cols; ++colCount) {
skyScape += " *";
if (colCount == cols - 1) {
skyScape += "\n";
}
}
}
}
public int getRows() {
return rows;
}
public int getCols() {
return cols;
}
public String getSky() {
return skyScape;
}
}
任何幫助,將不勝感激!
Java要求每個構造函數(Object除外)都調用一些超類構造函數,以確保初始化超類中包含的數據。 如果不顯式調用超類構造函數,編譯器將插入對超類的默認(零參數)構造函數的隱式調用。
您的構造函數調用基類構造函數。 否則,基類的成員將無法使用。
沒有任何錯誤。 每當instantiate
化子類時, 必須在執行子類構造函數之前調用超類構造函數。
當你正在擴展Star類時, Knight extends Stars
,Stars類也被加載到Knight類中,因此構造函數也被調用了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.