Bob Ivanovich wrote:I'm really confused as to what class is truly getting instantiated and how BankAccount and SavingsAccount are both functioning to help make the object 'b'.
The key point of confusion is that 'b' is NOT an object. It's a variable which can contain a reference to an object. So there are two separate things here: the variable 'b', which is of type BankAccount, and the object it refers to, which is of type SavingsAccount.
Now presumably SavingsAccount is a subclass of BankAccount (you didn't mention that but it seems like a reasonable assumption given the question), so it's legitimate to assign a reference to a SavingsAccount object to the variable 'b'. And then as far as the compiler knows, 'b' is of type BankAccount so it can only use methods which belong to BankAccount. This is
polymorphism at work; any object of a subclass of BankAccount can be assigned to a BankAccount variable and
treated as a BankAccount.
Now if you actually want your SavingsAccount object to be treated as a SavingsAccount, so that you can use methods which don't belong to its subclass BankAccount, then you have to assign it to a SavingsAccount variable. However if you find yourself having to downcast like that a lot, it's possible that you might want to reconsider the design which makes you do that. Perhaps addInterest() could be a method in the BankAccount class -- perhaps even an abstract method, with different implementations for different subclasses.