I have just started learning java and I have two basics questions. My main() looks like this:
public class Main {
public static void main(String[] args) {
Storage<BankAccount> aStorage = new Storage<BankAccount>();
Storage<String> sStorage = new Storage<String>();
Class baCls = BankAccount.class;
try {
Object myAccount = baCls.newInstance();
aStorage.setValue( myAccount );
myAccount.deposit( 15 );
}
catch ( InstantiationException e ) {
}
catch ( IllegalAccessException e ) {
}
}}
Why do I get these errors:
- The method deposit(int) is undefined for the type Object
- The method setValue(BankAccount) in the type Storage is not applicable for the arguments (Object).
After that I tried to replace:
Object myAccount = baCls.newInstance();
with
BankAccount myAccount = baCls.newInstance();
But then I am getting this error:
- Type mismatch: cannot convert from Object to BankAccount
I know that the right way would be:
BankAccount myAccount = (BankAccount) baCls.newInstance();
But I am not really sure that I understand why... I tried to read about it from a various sources so I have a few theories, but I still cannot wrap my head around this properly. Can someone please help me understand?
P.S. Sorry for posting such a basic question.
Object#newInstanceinstead of something likeBankAccount myAccount = new BankAccount()?