我试图将值传递给名为“account”的超类,然后将每个obj存储到数组列表中。
我的类帐户代码
abstract class account{
String number;
String name;
int amount;
int newbalance;
static final int balance = 1000;
int bal;
public account(){
// used to store the parameter passed into constructor
}
int deposit(int i) {
return i;
}
void withdrawal(int i){
}
public void setData(String string, String string2, int i) {
// TODO Auto-generated method stub
}
public void showData() {
// TODO Auto-generated method stub
}
}
在main方法中,我希望创建一个对象,然后传入要存储在数组列表中的name,number和amount值,因为我希望为它们存储具有不同名称number和amount的多个对象。 然后我想访问子类“sbaccount”并更新“newbalance”变量
我的主代码
public class oopassignment {
public static void main(String[] args) {
String type;
Scanner input = new Scanner (System.in);
System.out.println("What type of account do you want to create? :");
type=input.nextLine();
Account sb;
sb = new sbaccount();
//sb.setData("Jospeh", "0563994",50000);
sb.setData("Joohn", "009734",50000);
sb.setData("hope", "05634",50000);
ArrayList <sbaccount> usera = new ArrayList<sbaccount>();
usera.add((sbaccount) sb);
usera.add((sbaccount) sb);
for (int i = 0; i < usera.size(); i++){
usera.get(i).showData();
//userb.
}
}
和子类“SBAccount”的代码
final class sbaccount extends Account {
int total = 0;
public sbaccount(){
super ();
}
public void setData(String name, String number, int amount){
this.name = name;
this.number= number;
this.amount= amount;
}
public void showData(){
System.out.println("Account Owner: "+name);
System.out.println("Account number: "+ number);
System.out.println("Your New Amount is "+ newbalance);
System.out.println("Your Account Balance is: $"+ total);
return;
}
int deposit ( int money){
newbalance = money + amount;
System.out.println("Hi "+ name
+" \nAccountnumber: "+ number
+" \nYou have deposited :$"+money);
System.out.println("\nYour Account balance is now :"+ newbalance);
return newbalance;
}
void withdrawal(int withdraw){
int total = 0;
total = bal - withdraw;
if (total <= balance){
System.out.println("Your balance is too low for withdrawal!");
}
else{
System.out.println("\nHi "+ name
+" \nAccountnumber: "+ number
+" \nYou have Withdrawn :$"+withdraw);
System.out.println("\nYour Account balance is now :"+ total);
}
}
}
首先,我建议您将每个类名的第一个字母按官方命名规则大写
之后,我在您的代码中没有看到任何编译错误。 而且就您的问题而言,您已经成功地为对象实现了arraylist。
还有一点,我想说的是,在添加到列表之前,您不需要强制转换对象,因为它是父类型的子类。
即以书面形式代替
usera.add((sbaccount) sb);
简单地使用
usera.add( sb);
编辑:
那么您的问题是为什么对象中的值不断被覆盖? 答案很简单。 因为你写了
sb.setData("Joohn", "009734",50000);
sb.setData("hope", "05634",50000);
这意味着首先在“sb”对象中设置数据,然后在同一个“sb”对象中更新数据。
要在数组列表中存储这两个数据,只需要两个对象,比如sb1和sb2。
Account sb1 = new Sbaccount();
sb1.setData("Joohn", "009734",50000);
Account sb2 = new Sbaccount();
sb2.setData("hope", "05634",50000);
....
usera.add(sb1);
usera.add(sb2);