10

別のクラスから継承するクラスに取り組んでいますが、「シンボル コンストラクター Account() が見つかりません」というコンパイラ エラーが発生します。基本的に私がやろうとしているのは、Account から拡張するクラス InvestmentAccount を作成することです - Account は、お金を引き出し/入金する方法で残高を保持することを目的としていますが、InvestmentAccount は似ていますが、残高は株価によってどのように決定されるかを示す株式に保存されます特定の金額を指定すると、多くの株式が預け入れまたは引き出されます。サブクラス InvestmentAccount の最初の数行 (コンパイラが問題を指摘したあたり) を次に示します。

public class InvestmentAccount extends Account
{
    protected int sharePrice;
    protected int numShares;
    private Person customer;

    public InvestmentAccount(Person customer, int sharePrice)
    {
        this.customer = customer;
        sharePrice = sharePrice;
    }
    // etc...

Person クラスは、別のファイル (Person.java) に保持されます。スーパークラス Account の最初の数行は次のとおりです。

public class Account 
{
    private Person customer;
    protected int balanceInPence;

    public Account(Person customer)
    {
        this.customer = customer;
        balanceInPence = 0;
    }
    // etc...

コンパイラが Account クラスから Account のシンボル コンストラクターを読み取るだけではない理由はありますか? それとも、すべてを継承するように指示する InvestmentAccount 内の Account の新しいコンストラクターを定義する必要がありますか?

ありがとう

4

5 に答える 5

25

s コンストラクターで使用super(customer)します。InvestmentAccount

Java は空のコンストラクターではないため、唯一のコンストラクターを呼び出す方法を知ることができません。基本クラスに空のコンストラクターがある場合にのみ省略できます。Accountsuper()

変化する

public InvestmentAccount(Person customer, int sharePrice)
{
        this.customer = customer;
        sharePrice = sharePrice;
}

public InvestmentAccount(Person customer, int sharePrice)
{
        super(customer);
        sharePrice = sharePrice;
}

それはうまくいきます。

于 2009-02-04T10:21:38.123 に答える
2

スーパークラス コンストラクターを呼び出す必要があります。そうしないと、Java は、サブクラスでスーパークラスを構築するために呼び出しているコンストラクターを認識できません。

public class InvestmentAccount extends Account {
    protected int sharePrice;
    protected int numShares;
    private Person customer;

    public InvestmentAccount(Person customer, int sharePrice) {
        super(customer);
        this.customer = customer;
        sharePrice = sharePrice;
    }
}
于 2009-02-04T10:28:45.427 に答える
1

基本クラスにデフォルトのコンストラクター (引数のないコンストラクター) がない場合は、基本クラスのコンストラクターを明示的に呼び出す必要があります。

あなたの場合、コンストラクターは次のようになります。

public InvestmentAccount(Person customer, int sharePrice) {
    super(customer);
    sharePrice = sharePrice;
}

customerまた、サブクラスのインスタンス変数として再定義しないでください!

于 2009-02-04T10:23:07.513 に答える
1

super() メソッドを呼び出します。Account(Person) コンストラクターを呼び出す場合は、ステートメント super(customer); を使用します。また、これは InvestmentAccount コンストラクターの最初のステートメントである必要があります

于 2009-02-04T10:23:39.913 に答える
1

Accountクラスでデフォルトのコンストラクターを定義します。

public Account() {}

またはsuper(customer)InvestmentAccountコンストラクターを呼び出します。

于 2009-02-04T10:23:55.217 に答える