2011-11-15 7 views
1

再び、私はjava n00bです。私はゼロから学び、いくつか厄介な問題にぶつかることを試みています。次のようにJavaインポートのエラー

私はAccountクラスを得た:私が使用しようとしていますAccount.java

public class Account 
{ 
    protected double balance; 

    // Constructor to initialize balance 
    public Account(double amount) 
{ 
    balance = amount; 
} 

    // Overloaded constructor for empty balance 
    public Account() 
{ 
    balance = 0.0; 
} 

    public void deposit(double amount) 
{ 
    balance += amount; 
} 

    public double withdraw(double amount) 
{ 
      // See if amount can be withdrawn 
    if (balance >= amount) 
    { 
     balance -= amount; 
        return amount; 
    } 
    else 
      // Withdrawal not allowed 
        return 0.0; 
} 

    public double getbalance() 
{ 
      return balance; 
} 
    } 

は、このクラスのメソッドと変数を継承するために拡張します。だから、私は、インポートエラーを言ってエラーが出るInterestBearingAccount.java

import Account; 

class InterestBearingAccount extends Account 
    { 
    // Default interest rate of 7.95 percent (const) 
    private static double default_interest = 7.95; 

    // Current interest rate 
    private double interest_rate; 

    // Overloaded constructor accepting balance and an interest rate 
    public InterestBearingAccount(double amount, double interest) 
{ 
    balance = amount; 
    interest_rate = interest; 
} 

    // Overloaded constructor accepting balance with a default interest rate 
    public InterestBearingAccount(double amount) 
{ 
    balance = amount; 
    interest_rate = default_interest; 
} 

    // Overloaded constructor with empty balance and a default interest rate 
    public InterestBearingAccount() 
{ 
    balance = 0.0; 
    interest_rate = default_interest; 
} 

    public void add_monthly_interest() 
{ 
      // Add interest to our account 
    balance = balance + 
        (balance * interest_rate/100)/12; 
} 

} 

を使用しました「」私がコンパイルしようとすると予想される。すべてのファイルは同じフォルダにあります。

私はjavac -cpを実行しました。 InterestBearingAccount

+3

同じパッケージに入っている場合は、インポートする必要はありません。 –

答えて

5

すべてのファイルが同じフォルダ/パッケージにある場合は、インポートする必要はありません。

1

クラスが同じパッケージにある場合は、インポートする必要はありません。それ以外の場合は、パッケージとクラス名をインポートする必要があります。

+0

さて、パッケージはなんですか?それはすべての必要なクラスを含むフォルダですか? – roymustang86

+0

あなたはインターネットで検索する方法を知っていますか? http://en.wikipedia.org/wiki/Java_package – hovanessyan

0

あなたのクラスを定義するときは、必要に応じてファイルの先頭にpackageステートメントを含めることができ

public class InterestBearingAccount {} 
3

のように、InterestBearingAccountクラスを公開します。これは、クラスが属するパッケージを要求し、ファイルシステム上のその位置に関連付ける必要があります。例えば、パッケージcom.fooの公共クラスAccountには、以下のファイル階層に定義されるべきである。

com 
| 
|--foo 
    | 
    |--Account.java 

あなたは両方のあなたのクラスが匿名パッケージに属しているpackage文を省略してきたように。同じパッケージに属するクラスの場合、クラスを参照するためにクラスをインポートする必要はありません。これは、別のパッケージに含まれるクラスの要件にすぎません。

+0

パッケージはフォルダの名前ですか? – roymustang86

+1

フォルダの階層はパッケージ名を表します。上記の例では、パッケージはcom.fooなので、Account.javaの最初の行に "package com.foo '"を追加します。 – Adamski

関連する問題