Reputation:
I have to create an Object of List in main Method but i have no idea how to do it. Constructor of class, that i want to create an Object has an List as a parameter.
How can i create an Object of CashMachine class?
By the way I am not going to write all of the classes, because it is long.
Here are my classes:
public class CashMachine {
private State state;
List<Account> accountList;
private CashCard cashCard;
private Account selectedAccount;
public CashMachine(List<Account> accountList){
this.accountList = accountList;
}
}
public class TestMain {
public static void main(String[] args) throws Exception {
CashMachine cashMachineObj = new CashMachine(); //it is false
}
}
Upvotes: 1
Views: 3535
Reputation: 271885
If you read the docs for List
, you will see that List
is actually an interface!
Interfaces are like protocols. The methods in interfaces don't have implementations. The classes that implement the interface must provide those implementations. You can't just create a new List
object by calling its constructor because it doesn't make sense to create an object with methods that have no implementations!
What you should do is to create an object of a class that implements List
, for example, ArrayList
.
ArrayList<Account> accounts = new ArrayList<>();
You can now pass accounts
to the constructor of CashMachine
.
Upvotes: 1
Reputation: 140467
You wrote a constructor, that wants a List ... so surprise, you have to provide one.
Simple, will compile, but is wrong:
CashMachine cashMachineObj = new CashMachine(null);
Better:
CashMachine cashMachineObj = new CashMachine(new ArrayList<>());
The above simply creates an empty list and passes that into the CashMashine.
In other words: there are many ways to create lists; and you can pick whatever approach you like. Even things like:
CashMachine cashMachineObj = new CashMachine(Arrays.asList(account1, account2));
where account1, account2 would be existing Objects of the Account class.
Upvotes: 1