Inheritance
Analogy:
animals
amphibians reptiles warm-blooded
birds mammals
cats rodents
As we go lower, more specialisation happens. Properties are 'inherited'
from above.
-
an important principle of OOP
-
allows us to add facilities to existing classes
-
allows us to exploit commonality at design stage ( 'is-a')
New keywords:
-
extends (inherits from)
-
protected - midway between private and public.
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:
-
GoldAccount can use any public or protected items of BankAccount (not its private items)
-
we have added a variable - overdraft
-
we have added a method - withdraw
-
we have overridden the withdraw of BankAccount with one in GoldAccount
-
Gold accounts will use their own withdraw, not the one in BankAccount.
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:
-
GoldAccount is a subclass of BankAccount(can be many)
-
BankAccount is the superclass of GoldAccount (one only)
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
-
if a method or variable is public, any class can use it.
-
if private, they can only be used within their class.
-
we strive to keep variables private, providing methods to access them.
-
Often, an inheritor may need to access its super's variables, as well as its methods.
-
protected - such items can be accessed by an inheritor (e.g 'expert' use)
but NOT when 'normal' use is happening. Normal use:
...
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.