Inheritance

Analogy:
              animals


     amphibians          reptiles  warm-blooded


                                        
                             birds     mammals


                                  cats      rodents

As we go lower, more specialisation happens. Properties are 'inherited' from above. New keywords: Example look at a classes based round a bank account. First an existing class:

class BankAccount {

    protected String name;     //nb was private
    protected int balance;

    public int getBalance() {
        return balance;
    }

    public void setBalance(int amount){
        balance = amount;
    }

    public void deposit(int amount) {
        balance = balance + amount;
    }

    public void withdraw(int amount){ 
        if(balance>= amount){   //enough in account?
            balance=balance-amount;
        }
    ...etc
    }

Now a gold account, which has an overdraft, set to 200:

class GoldAccount extends BankAccount {
    private overdraft = 200;   

    public void withdraw(int amount){
        if((balance+overdraft)>=amount){
            balance=balance-amount;
        }       
    }
}

points:

Examples of use:


GoldAccount g;
BankAccount b;
g=newGoldAccount();
b=new BankAccount();
...
g.deposit(30);
b.deposit(30);

g.withdraw(10;
b.withdraw(10);
Jargon: NB - 'super' does not mean 'more powerful than'

Mechanism

Java looks for a method in the class of the object, as declared.

If not found, a search is made in the super ...etc.. etc.

In Java, there is a class named Object, at the top of the tree. Even Sphere inherits from this!

The search for a matching method ends in Object. There is an error if the method is never found.

Scope Rules

Ideally you can plan for inheritance by using protected, rather than private. - to avoid the programmer having to edit the class.

Spotting Inheritance

In the design stage , we have some nouns. Apply 'IS-A kind of' to them:

book, user, cd, library, manager, worker, journal ...

Summary

Inheritance can be used to plan a set of related classes - or to enhance an existing class.

VB6 does not have inheritance, but VB.NET does.