Reputation: 43
i have Bank class, with a private static ArrayList that stores all the banks. how can i add every new bank created to it? i'm not allowed to create any new methods or fields, or change any of the method or constructor parameters.
this is my Bank class:
public class Bank {
private static ArrayList<Bank> allBanks=new ArrayList<Bank>();
private String name;
public Bank(String name) {
this.name = name;
}
public String getName() {
return name;
}
and this is my Main class:
public class Main {
public static void main(String[] args) {
new Bank("randomBankName");
}
}
Upvotes: 0
Views: 728
Reputation: 700
You didn't say, that you may not change the visibility of fields, so that would be one way to do this: make the ArrayList
public
If you may not do this either, there is a last way, which i'd never do: Reflection. In most cases, thats really the last way, not recommended!
Upvotes: 0
Reputation: 20534
Do it in constructor:
public Bank(String name) {
this.name = name;
allBanks.add(this);
}
WARNING never do it in real project.
Upvotes: 3