Call the child method when converting to the parent type in Java
I am trying to complete some course work. Any help will be appreciated!
I have three types of accounts that extend the abstract type "account" [currentaccount, staffaccount and mortgageaccount]
I try to read some data from the file and create account objects and user objects to add to the hash map stored in the program
When I create an account object, I use a temporary variable of account type and define its subtype according to the read data
For example:
Account temp=null; if(data[i].equalsIgnoreCase("mortgage"){ temp= new MortgageAccount; }
The problem is when I try to call a method of type mortgageaccount
Do I need each type of temporary variable, staffaccount, mortgageaccount and currentaccount, and use them corespondingly to use their methods?
Thank you in advance!
Solution
It depends on If the parent account overrides a method in the mortgageaccount, you will get the mortgageaccount version when you call the method If the method exists only in the mortgageaccount, you need to convert the variable to call the method