【发布时间】:2014-06-24 02:15:28
【问题描述】:
如果我有三门课。一类A,一类Customer,我在构造函数中放置了A 的ArrayList,还有一类SavingsAccount,我想将它们放在一起。在课堂上A 我有一个方法,我想从SavingsAccount 调用。我怎么做?并同时呼叫Customer 和SavingsAccount?
在Customer 中有一个变量; SocSecNr,必须匹配SavingsAccount 中的Nr,才能在A 中正确,这就是为什么我将SavingsAccount 的ArrayList 放在Customer 中。
(这只是一个示例类。我只想知道如何在没有继承的情况下进行此调用)
import java.util.ArrayList;
public class A {
private ArrayList<Customer> customerlist;
private SavingsAccount account;
public A() {
customerlist = new ArrayList<Customer>();
account = new SavingsAccount();
}
public boolean deposit(long pNr, int accountId, double amount)
{
for(int i = 0; i < customerlist.size(); i++)
{
if(customerlist.get(i).getPCode() == pNr)
{
account.transaction(amount);
}
}
return false;
}
public double transaction(){
if(amount < 0 && balance + amount < 0)
return -0;
else
return balance += amount;
}
public class Customer {
private long pNr;
private ArrayList<SavingsAccount> accounts;
public Customer(long pCode)
{
pNr = pCode;
accounts = new ArrayList<SavingsAccount>();
}
public ArrayList<SavingsAccount> getAccount(){
return accounts;
}
}
public class SavingsAccount {
private double balance;
public SavingsAccount(){
accountId = accountCount;
}
public double transaction(double amount){
if(amount < 0 && balance + amount < 0)
return -0;
else
return balance += amount;
}
}
【问题讨论】:
-
类和属性是不同的东西
-
你的类名应该以大写字母开头,这样代码更容易理解。
-
那么,在 A 中你有一个 B 元素的 ArrayList,还是一些通用的
type的 ArrayList?如果是这样,为什么你把它称为 b,作为另一个类的名称? -
这些不是我的实际课程,只是一个例子。我想知道如何从a类进入c的方法的原理。我已经尝试使用 c.callThisMethod(x) 但只得到错误。
-
@Keppil 我改进了我的代码,希望现在更容易理解。
标签: java class methods arraylist callback