Java - extends似乎是在调用其他类的构造函数

时间:2012-01-14 07:24:28

标签: java inheritance constructor extends

我正在尝试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         import 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;
    }
}

任何帮助将不胜感激!

4 个答案:

答案 0 :(得分:2)

Java要求每个构造函数(Object除外)都调用一些超类构造函数,以确保初始化超类中包含的数据。如果没有显式调用超类构造函数,编译器将插入对超类的默认(零参数)构造函数的隐式调用。

答案 1 :(得分:0)

您的构造函数调用基类构造函数。否则,基类的成员将无法使用。

答案 2 :(得分:0)

没有错。每当你instantiate子类时,必须在执行子类构造函数之前调用超类构造函数

答案 3 :(得分:0)

当您扩展Star类Knight extends Stars时,Stars类也会在Knight类中加载,因此构造函数也会被调用。