Reputation: 1097
I am doing homework in C# in which I am implementing the abstract class of Account then I derived two classes form Account named as Saving Account and Checking Account and override some methods in derived classes. Now my problem statement says
Only Instantiate SavingAccount and CheckingAccount Through a reference of Account
Now I am unable to write the code of this because I know the simple object creation but I don't know how to create an object through the reference of an object. Please tell me some syntax. Thanx
Upvotes: 1
Views: 144
Reputation: 4702
If you want to create a SavingAccount or CheckingAccount from an instance of Account that you already have then you can cast it as
one of those accounts. Like so -
int _accountID = 356;
Account _account = new SavingsAccount(_accountID);
// now to create a SavingAccount or CheckingAccount from _account
SavingAccount _savingAccount = _account as SavingAccount;
Upvotes: 0
Reputation: 4561
The idea is that an identifier can be the base type:
SomeBaseType identifier;
But when you instantiate it (or new up an instance), you can use any derived type
e.g.
Account account = new SavingsAccount();
EDIT I wanted to add that this is where OOP comes to life (read: "gets really fun!"). Now you can design an interface
or contract (such as with an Account
class) - and program to the one design. But you may have different account types actually used. With the example I gave, account
will continue to look like an Account
. Any 'new' methods or features in SavingsAccount
will not be immediately visiable to code using your account
variable. But that's okay! You don't want your code to be specifically tailored to SavingsAccount
(in MOST cases), you want to instead design a flexible Account
that can represent the basic and common features of any Account
.
Upvotes: 5