• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inheritance relationship between the type of the actual object and the object reference.  RSS feed

 
Bob Ivanovich
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For example I create an object like this:



Now lets say that I want to access a method 'addInterest()' that is in the 'SavingsAccount' class I would have to do: '((SavingsAccount)s).addInterest();'


The question I have is why do I have to cast 'b' to SavingsAccount? Isn't the actual object reference of 'b' already an instance of 'SavingsAccount' class? How does the 'BankAccount' affect the object itself? 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'.

I appreciate any help. Thank you.
 
Paul Clapham
Sheriff
Posts: 22844
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!