如何获得一个类的实例? [英] How to get an instance of a class?
本文介绍了如何获得一个类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码
class driver{
static BankAccount GetAccount(Customer customer, char c) {
BankAccount accSrc = customer.S;
// savings account
if (c =='S') {
accSrc = customer.S;
// loan account
} else if (c =='L') {
accSrc = customer.L;
// checking account
} else if (c =='C') {
accSrc = customer.C;
// auto loan account
} else if (c =='A') {
accSrc = customer.A;
}
return accSrc;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer forrest = new Customer("Forrest Gump", 1, "42 New Street, New York, New York"); // me
Customer random = new Customer("Random Name", 2, "44 New Street, New York, New York"); // imaginary partner
//try{
String input = JOptionPane.showInputDialog("Please enter your transaction information: ");
Scanner s = new Scanner(input);
int id = Integer.parseInt(s.next());
char action = Character.toUpperCase((s.next().charAt(0)));
char accSrc = ' ';
char accDest = ' ';
double amount = 0;
if(action == 'T'){
amount = s.nextDouble();
accSrc = s.next().charAt(0);
accDest = s.next().charAt(0);
}else if(action == 'G' || action == 'I'){
accSrc = s.next().charAt(0);
}else{
//if D,W
amount = s.nextDouble();
accSrc = s.next().charAt(0);
}
//}catch (IOException e){
//}
if(id==1){
return forrest;
}else if(id == 2){
return random;
}
BankAccount src = GetAccount(forrest, accSrc);
System.out.print(src.getOwner().name);
if(action == 'T'){
BankAccount dst = GetAccount(forrest, accDest);
src.transfer(amount, dst);
.
..
}
class Customer{
protected String name;
protected int id;
protected String address;
protected BankAccount C = new BankAccount(id, this, 0);
protected BankAccount S = new BankAccount(id, this, 0);
protected BankAccount A = new BankAccount(id, this, 0);
protected BankAccount L = new BankAccount(id, this, 0);
...
}
当前正在对银行帐户<$ c $进行硬编码c> src = GetAccount(forrest,accSrc); 我该如何继续编写代码,以便它返回给定id号的客户实例(例如1个给定的forrest回报,2个给定的随机回报)?
currently im hard coding BankAccount src = GetAccount(forrest, accSrc);
how can I proceed to writing code so it returns an instance of the customers given an id number (say 1 given returns forrest, 2 given returns random) ?
推荐答案
更好的
Customer customers[] = { forrest, random };
我可以使用 customer [id] $ c $调用实例c>
这篇关于如何获得一个类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文