繁体   English   中英

如何在Java中使用来自不同类的方法?

[英]How can I use methods from a different class in Java?

我试着搜索这个问题,但找不到任何真正帮助我的东西..

我有一个Java文件,其中包含一个银行帐户类,其中包含存入,退出,更改名称,收取服务费以及打印帐户摘要的方法。 该文件名为Account.java

当我尝试运行此程序时,我收到一条消息,指出文件中没有找到主要方法。

那么我还有另一个名为ManageAccount.java的文件,它应该使用Account类来创建和管理2个不同的银行账户。 这个文件只有说明(评论形式),只有3行代码,我的教授包括:

    public class ManageAccounts { 
    public static void main(String[] args){ 
    Account acct1, acct2; 

我对如何将两个文件链接在一起感到困惑。 在ManageAccount文件中,我在开头添加了这两行:

    package Account; 
    import Account.*; 

我该怎么办? 如何在ManageAccounts类的Account类中使用withdraw,deposit,changeName,serviceFee和printSummary方法?

首先来看看oop的基础知识。 在您的main方法中,按新方法创建两个新的帐户实例。

  public static void main(String[] args){ 
    Account acct1 = new Account(1000,"Sally",1111); 
    Account acct2 = new Account(1000,"Barry",1112);
    acct1.depositTo(2000);

}

在变量acct1和acct2中,您有两个Account类实例。 帐户类是您的实例的某种形状。 在实例上,您可以调用已定义的方法。 如果要运行程序,则必须在定义main方法的类上运行它。

为了能够启动Java程序,您需要一些代码来开始。 这是主要方法。 这是一个如何看的例子。

public static void main(String[] args) {

}

当然这个主要方法什么都不做。 所以你需要在方法中插入你的代码。 您还需要记住,能够调用您需要的方法来创建您要使用的类的实例(除非该方法是静态的)请查看http://docs.oracle.com/javase / tutorial / java / concepts /学习基础知识。

由于您没有发布所有代码和错误消息,因此很难回答这个问题。 如果A类的命令能够使用B类的方法,则需要在A类项目的构建路径中设置B类。 最简单的方法是将它们放在同一个包中,这样它们就可以互相看见(假设方法不是私有的)。

我认为你没有清楚自己的基础知识,所以首先阅读OPPS的概念并开始使用,以便将来可以避免错误。要访问其他类中的方法,可以创建实例并使用它访问相应的方法。 检查以下示例,以便您了解..

public class Account {
int id;
Date dateCreated;
double balance, annualInteretRate;
// Other fields

public Account() {
// Here is where you create a default account.
}

public void setID(int i) {
id = i;
}

public int getID() {
return id;
}

// Method that checks to see if balance is sufficient for withdrawal.
// If so, reduces balance by amount; if not, prints message.
public void withdraw(double amount)
{
if (balance >= amount)
{
balance -= amount;
}
else
{
System.out.println("Insufficient funds");
}
}

// Method that adds deposit amount to balance.
public void deposit(double amount)
{
balance += amount;
}
//-----------------------------------…
// Returns balance.
//-----------------------------------…
public double getBalance()
{
return balance;
}
// Adds interest to the account and returns the new balance.
/
public double addInterest ()
{
balance += (balance * RATE);
return balance;
}

///主要课程

import java.util.Scanner;

public class BankProgram {
public static void main(String args[]) {
Account acct1 = new Account();
acct1.setID(1122);
acct1.setBalance(20000);
acct1.setAnnualInterestRate(4.5);
System.out.print("\nDepositing $3000 into account, balance is now ");
acct1.deposit(3000);
System.out.println(acct.getBalance());
System.out.print("\nWithdrawing $2500, balance is now ");
acct1.withdraw(2500);
System.out.println(acct.getBalance());
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM