簡體   English   中英

初始化類型抽象類的ArrayList

[英]Initialize ArrayList of Type Abstract class

我想在抽象類類型的數組列表中填充值。下面是我的代碼

public abstract class Account {
    private int accountId;
    private int customerId;
    private double balance;

    public Account(int accountId, int customerId, double balance) {
        this.accountId = accountId;
        this.customerId = customerId;
        this.balance = balance;
    }

    public abstract double deposit(double sum);
    public abstract double withdraw(double sum);
}

上面是我的抽象類。 現在我有另一個類bank中,我想定義並宣布an arraylist中,我可以填補我的價值觀。 我宣布arraylist為

ArrayList<Account> al=new ArrayList<>();

現在我想將值傳遞給該數組列表以供進一步使用,但由於無法實例化抽象類而無法執行。我嘗試使用此代碼使用main方法將類中的值填充,但由於上述原因而無法獲取它

Account ac= new Account(1,100,25000);
    ArrayList<Account>ac= new ArrayList<Account>();
    ac.add(ac);

抽象類無法實例化,但可以擴展。 如果子類是具體的,則可以實例化它。

您還必須實現兩種抽象方法,以使類具體化。

在此處閱讀更多內容: Java繼承

您的抽象類的全部重點是分解應用程序中的某些代碼。 在我看來,將其用作超級類型是一種不好的做法,因為您應該為此使用接口。

為了得到您問題的完整答復,我將:

創建一個接口:Account.java

public interface Account {
    public double deposit(double sum);
    public double withdraw(double sum);
}

創建一個抽象類:AbstractAccount.java

public abstract class AbstractAccount {
    protected int accountId;
    protected int customerId;
    protected double balance;
    public Account(int accountId, int customerId, double balance) {
        this.accountId = accountId;
        this.customerId = customerId;
        this.balance = balance;
    }
}

最后為您的接口BankAccount.java提供一個默認實現。

public class BankAccount extends AbstractAccount implements Account {
    public Account(int accountId, int customerId, double balance) {
        super(accountId, customerId, balance);
    }
    public double deposit(double sum) {
        this.balance += sum;
    }
    public double withdraw(double sum) {
        this.balance -= sum;
    }
}

然后,您應該進行以下操作:

List<Account> accounts = new ArrayList<Account>();
accounts.add(new BankAccount(1, 1, 10000));

從來不在乎實現類型:)

您可以添加以下代碼只是為了入門:

public class ConcreteAccount extends Account{
    public ConcreteAccount (int accountId, int customerId, double balance) {
        super(accountId, customerId, balance);
    }

    public abstract double deposit(double sum) {
       //implementation here
    }
    public abstract double withdraw(double sum) {
       //implementation here
    }
}

然后,您可以擁有:

Account ac= new ConcreteAccount(1,100,25000);
ArrayList<Account> acList= new ArrayList<Account>();
acList.add(ac);

標記一個抽象類意味着它可能具有未實現的方法,因此,由於行為未定義,您不能直接創建抽象類的實例。 您可以做的是定義一個非抽象類,該類擴展您的Account類並在Account實現兩個抽象方法。 諸如class BankAccount extends Account { implementations }東西class BankAccount extends Account { implementations } 然后,您可以創建BankAccount類的實例,並將其添加到ArrayList實例中。 擴展Account的類的其他實例也可以添加到ArrayList實例中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM