Example of single inheritance: A bank will have different kinds of accounts, and yet they are all accounts. If we consider checking accounts and savings accounts, they have a number of common features, they both have an owner and a balance. They also have some different features, the fact that checks are allowed for one and the other pays interest. It makes sense to have a basic account class that contains the common parts and then to use inheritance to define the checking account and the savings account subclasses. Thus the account class defines what is common to all accounts; the checking account class defines what is specific to checking accounts; and the savings account class defines only what is specific to savings accounts. Any changes to the account class will be picked up by the inheriting classes automatically. |
These relationships can be represented as shown in the figure below. In the example shown, each instance of CheckingAccount is automatically created with memory allocated for the attributes account-number, balance, date-opened and charges. Additionally, the methods deposit, withdraw, and balance inherited from Account and the methods displayCharges and calculateCharges defined in the CheckingAccount class can act on each instance. Each instance of SavingsAccount is automatically created with memory allocated for the attributes account-number, balance, date-opened and interest-rate. Each instance of SavingsAccount can access the methods deposit, withdraw and balance inherited from Account and the method calculateInterest defined for itself. Some sample code for the account and checking account classes is shown below: Account Class CLASS-ID. Account INHERITS Base. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY CLASS Base. FACTORY. DATA DIVISION. WORKING-STORAGE SECTION. 01 number-of-accounts PIC 9(5). PROCEDURE DIVISION. METHOD-ID. newAccount. method code END METHOD. |
... END FACTORY. OBJECT. DATA DIVISION. WORKING-STORAGE SECTION. 01 ACCOUNT-INFORMATION. 03 account-number PIC X(12). 03 balance PIC S9(8)V99. 03 date-opened PIC 9(8). ... PROCEDURE DIVISION. METHOD-ID. deposit. ... END METHOD. METHOD-ID. withdraw. ... END METHOD. METHOD-ID. balance. ... END METHOD. ... CheckingAccount Class CLASS-ID. CheckingAccount INHERITS Account. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. CLASS Account. ... OBJECT. DATA DIVISION. WORKING-STORAGE SECTION. 01 checking-account 03 charges PIC S9(8)V99. ... PROCEDURE DIVISION. METHOD-ID. displayCharges. ... END METHOD. METHOD-ID. calculateCharges. ... END METHOD. ... |