2011-11-15 76 views
1

同樣,我是一個java n00b,我試圖從頭學習並遇到一些令人尷尬的問題。Java導入給出錯誤

我得到了一個賬戶類,如下所示: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

SO,包裝究竟是什麼?它是一個包含所有必需類的文件夾嗎? – roymustang86

+0

你知道如何在互聯網上搜索,對吧? http://en.wikipedia.org/wiki/Java_package – hovanessyan

0

化妝InterestBearingAccount班公像

public class InterestBearingAccount {} 
3

當你定義類,你可以任選包括在文件的頂部package聲明。這規定了該類所屬的包,並且應該與文件系統上的位置相關聯。例如,在包裝com.foo一個公共類Account應在以下文件的層次結構來定義:

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

當你省略了package聲明既你的類屬於匿名包。對於屬於同一個包的類,不需要導入類來引用它們;這只是對不同包中類的一個要求。

+0

包是文件夾的名稱? – roymustang86

+1

文件夾的層次結構代表軟件包名稱。在上面的例子中,包是com.foo,所以你可以在Account.java中添加「package com.foo'」作爲第一行。 – Adamski