2011-11-15 111 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