Casting Objects

Casting shows the use of an object of one type in place of another type, among the objects permitted by inheritance and implementations

Consider the following code fragment:

Account fredsAccount = new Account(...);
SavingsAccount fredsSavingAccount = new SavingsAccount(...);
fredsAccount = fredsSavingAccount; /* OK */
fredsSavingAccount = fredsAccount; /* fail */


In the first object assignment, the compiler implicitly casts a SavingsAccount type to an Account type. This is done because all instances of SavingsAccount are also instances of Account (upcasting). The second object assignment fails at compilation since we are attempting to implicitly downcast an Account type to a SavingsAccount. Not all instances of Account are also instances of SavingsAccount even though in our example we know that fredsAccount contains an instance of SavingsAccount. We must explicitly downcast, so the following statement would be valid:

fredsSavingAccount = (SavingsAccount) fredsAccount;

No comments:

Post a Comment