Transcript Ch14

Class Inheritance
• Class inheritance in contrast to interface
inheritance.
– They have polymorphism in common.
• A fundamental feature of OO languages.
• Gives OO languages much of their power.
• A facility that supports code reuse.
OOP with Java, David
J. Barnes
Class Inheritance
1
Common Characteristics
• Classes within a problem domain are often
closely related.
– The relationship is often hierarchical.
• Grandparent - Parent - Child.
• Parent - Child/Child (siblings).
– Cargo Ship, Passenger Ship, Ferry, Dinghy, etc.
OOP with Java, David
J. Barnes
Class Inheritance
2
Alternatives to Inheritance
• Implement each new class from scratch.
• Define a 'do-it-all' class.
• Use a 'type' field to select behavior
(tagging).
OOP with Java, David
J. Barnes
Class Inheritance
3
Problems with Alternatives
• Potentially a lot of duplication.
• No guarantees that an object will not be
used inappropriately.
• Programming out inappropriate use is
potentially tricky.
OOP with Java, David
J. Barnes
Class Inheritance
4
Object Tagging
class Boat {
// Possible types of boat.
public static int CargoShip = 0, PassengerShip = 1,
Ferry = 2;
public Boat(int type){
this.type = type;
}
public void loadCargo(Cargo c){
if(getType() != PassengerShip){
...
}
else{
...
}
}
...
}
OOP with Java, David
J. Barnes
Class Inheritance
5
Delegation
• A more promising alternative.
• Common behavior defined in delegate class.
• Specialist classes relay common-behavior
messages to a delegate attribute.
• Specialists define their own behavior.
• Common in the I/O classes.
OOP with Java, David
J. Barnes
Class Inheritance
6
class CargoShip {
public CargoShip(String name){
ship = new Ship(name);
}
public void setCourse(double c){
getShip().setCourse(c);
}
public void loadCargo(Cargo c){
addCargo(c);
}
...
private Ship getShip(){
return ship;
}
private final Ship ship;
}
OOP with Java, David
J. Barnes
Class Inheritance
7
Advantages of Inheritance
• Common elements in super class.
• Distinctive elements in sub classes.
• No duplicate methods required.
– Sub class derives behavior from super class.
• Objects are aware of their own type without
the need for tagging.
OOP with Java, David
J. Barnes
Class Inheritance
8
An Example of Inheritance
• Variety of heating controllers.
– Basic (shared) functionality.
• On or off.
– More sophisticated functionality.
• Temperature setting.
• On/off time periods.
• Possibly others.
OOP with Java, David
J. Barnes
Class Inheritance
9
HeaterController Super Class
class HeaterController {
public void switchOn(){
setOn(true);
}
public void switchOff(){
setOn(false);
}
public boolean isOn(){
return getOn();
}
...
}
OOP with Java, David
J. Barnes
Class Inheritance
10
Extending HeaterController
class VariableController extends HeaterController {
public static final int DefaultLevel = 16, ...;
public int getLevel(){
return getHeater().getTemperature();
}
public void setLevel(int level) throws RuntimeException {
if((MinLevel <= level) && (level <= MaxLevel)){
getHeater().setTemperature(level);
}
else{
throw new RuntimeException(
"Illegal level setting: "+level);
}
}
}
OOP with Java, David
J. Barnes
Class Inheritance
11
A VariableController Object
• Use like a VariableController or
HeaterController.
VariableController v = new VariableController();
...
// Warm up the room.
v.switchOn();
if(v.getLevel() == v.MinLevel){
v.setLevel(v.DefaultLevel);
}
...
// The room is warm enough - switch the heater off.
v.switchOff();
OOP with Java, David
J. Barnes
Class Inheritance
12
Polymorphism
• A sub class object may be used anywhere
that an object of its super class is required.
• Compare this with interfaces and their
implementing classes.
OOP with Java, David
J. Barnes
Class Inheritance
13
The Is-A Relationship
• Sub class/super class often characterized in
this way.
– VariableController is a
HeaterController.
– Circle is a Shape, Rectangle is a
Shape, Square is a Rectangle.
• The relationship is one way.
– Rectangle is not necessarily a Square.
OOP with Java, David
J. Barnes
Class Inheritance
14
Is-A versus Has-A
• A common linguistic confusion.
– Often responsible for inappropriate class structures.
• PCDatabase has a LinkedList attribute.
• PCDatabase is not a LinkedList.
• VariableController has a level attribute.
• VariableController is a HeaterController.
OOP with Java, David
J. Barnes
Class Inheritance
15
Issues in Inheritance
•
•
•
•
•
•
Inappropriate Inheritance.
Multiple Inheritance.
Downcasts and Upcasts.
Inheritance for Specialization.
Structural Similarity of Classes.
Order of Initialization and Super Class
Constructors.
OOP with Java, David
J. Barnes
Class Inheritance
16
Inappropriate Inheritance
import java.util.Random;
// Inappropriate inheritance
class Die extends Random {
// Return an integer in the range 1..6
public int roll(){
final int range = 6;
// Use the inherited nextInt method.
return 1+nextInt(range);
}
}
• java.util.Stack
OOP with Java, David
J. Barnes
extends java.util.Vector
Class Inheritance
17
A Proper Die Class
import java.util.Random;
class Die {
// Return an integer in the range 1..6
public int roll(){
final int range = 6;
return 1+getRand().nextInt(range);
}
protected Random getRand(){
return rand;
}
private final Random rand = new Random();
}
OOP with Java, David
J. Barnes
Class Inheritance
18
Multiple Inheritance?
• A class may extend only a single class.
• A class may implement multiple interfaces.
– In addition to extending a single class.
• An interface may extend multiple interfaces.
– interface ParentTeacher extends Parent, Teacher
OOP with Java, David
J. Barnes
Class Inheritance
19
Downcasts and Upcasts
• The terminology relates to the inheritance
hierarchy: up or down.
// Explicit downcasting.
// Downcast: Object -> String.
String s = (String) iterator.next();
// Implicit upcasting
VariableController v = new VariableController ();
// Upcast: HC <- VC.
HeaterController h = v;
OOP with Java, David
J. Barnes
Class Inheritance
20
Inheritance for Specialization
• Sub classes are often more specialized versions
of their super classes.
– java.io.LineNumberReader
• A supermarket's SellableItem class
extended to add a sell-by date.
– class PerishableItem extends SellableItem
• Sub class has everything (and more).
OOP with Java, David
J. Barnes
Class Inheritance
21
Library LoanItem
class LoanItem {
...
public String getTitle(){
return title;
}
public String getAccessionNumber(){
return accessionNumber;
}
private final String title, accessionNumber;
}
OOP with Java, David
J. Barnes
Class Inheritance
22
Book Sub Class
• Details of authors and length added.
class Book extends LoanItem {
...
public int getNumPages(){
return numPages;
}
// Allow for multiple authors.
private final String[] authors;
private final int numPages;
}
OOP with Java, David
J. Barnes
Class Inheritance
23
MusicCD Sub Class
• Details of artists and track numbers added.
class MusicCD extends LoanItem {
...
public int getNumTracks(){
return numTracks;
}
// Allow for multiple artists.
private final String[] artists;
private final int numTracks;
}
OOP with Java, David
J. Barnes
Class Inheritance
24
Structural Similarity
• Book and MusicCD have similar
structures.
– Don't be tempted to meld them into a single
class.
– Future changes difficult to include sensibly.
• CD playing time, for instance.
– Behavioral similarity more relevant.
OOP with Java, David
J. Barnes
Class Inheritance
25
Sub Class Initialization
• The super class elements of a sub class
object must be properly initialized.
– VariableController on/off state.
• Super class elements initialized first.
– Super class constructor selection is necessary.
– Argument passing must be arranged.
OOP with Java, David
J. Barnes
Class Inheritance
26
Super Class Constructors
class Bookmark implements Serializable {
public Bookmark(String url,String title){
this.url = url;
setTitle(title);
}
...
}
class AnnotatedBookmark extends Bookmark {
public AnnotatedBookmark(String url,String title,
String description){
super(url,title);
setDescription(description);
}
...
}
OOP with Java, David
J. Barnes
Class Inheritance
27
Super Class Construction (cont.)
• super must be called as first statement.
• No-arg super class constructor called by
default.
– Sub class error if the super class does not have
one.
– All classes without any constructor have a
default no-arg constructor.
OOP with Java, David
J. Barnes
Class Inheritance
28
Default No-Arg Constructor
class VariableController extends HeaterController {
public VariableController(int initialLevel) throws ... {
setLevel(initialLevel);
}
...
}
// Implicit extension of Object super class.
class HeaterController extends Object {
// Default (implicit) no-arg constructor.
public HeaterController(){
// (Implicit)
super();
}
...
}
OOP with Java, David
J. Barnes
Class Inheritance
29
Creating Exception Sub Classes
• Trivial sub class implementations.
– Additional functionality often not added.
– Only constructors required.
• Used to provide more detailed typing for
exception situations.
OOP with Java, David
J. Barnes
Class Inheritance
30
HeaterLevelException
class HeaterLevelException extends RuntimeException {
public HeaterLevelException(String message){
// Pass on the error message to the super class.
super(message);
}
public HeaterLevelException(){
}
}
OOP with Java, David
J. Barnes
Class Inheritance
31
Throwing Sub Class Exceptions
• User-defined exception class instances are
thrown and caught in the usual way.
public void setLevel(int level) throws HeaterLevelException {
if((level < MinLevel) || (level > MaxLevel)){
throw new HeaterLevelException(
"Illegal level setting: "+level);
}
...
}
OOP with Java, David
J. Barnes
Class Inheritance
32
Access Control Issues
• Inheritance means we need to revisit issues
of access control.
– What rights does a sub class have over its super
class members?
– Classes in one package might extend classes
defined elsewhere.
OOP with Java, David
J. Barnes
Class Inheritance
33
Access Control Rules
• public access is global.
• private access is class only.
– Sub classes have no rights.
• package access is whole package.
• protected access is package plus sub
classes.
OOP with Java, David
J. Barnes
Class Inheritance
34
package generations;
class Grandparent {
public int getTop(){
return top;
}
void setTop(int t){
top = t;
}
private int top;
}
class Parent extends Grandparent {
public int getMiddle(){
return middle;
}
protected void setMiddle(int m){
middle = m;
}
private int middle;
}
OOP with Java, David
J. Barnes
Class Inheritance
35
The Object Class
• The ultimate super class of all classes.
• Defines default versions of common
methods.
– public: equals, toString, getClass,
hashCode.
– protected: clone.
OOP with Java, David
J. Barnes
Class Inheritance
36
Default Object Behavior
• equals - reference equality.
• toString - "class@hashCode".
• getClass - Class object for type.
• hashCode - a computed hash code.
• clone - an identical copy.
OOP with Java, David
J. Barnes
Class Inheritance
37
The toString Method
• Invoked, by default, in contexts requiring a
String in place of an object reference.
class Object {
public String toString(){
return getClass().getName()+"@"+
Integer.toHexString(hashCode());
}
...
}
OOP with Java, David
J. Barnes
Class Inheritance
38
Overriding Methods
• Sub class specializations often need to
modify super class behavior.
– The default behavior of equals only mimics
reference equality (==).
– clone only creates a shallow copy, not a deep
copy.
OOP with Java, David
J. Barnes
Class Inheritance
39
class Point {
...
public String toString(){
return "("+getX()+","+getY()+")";
}
public boolean equals(Object o){
if(o == this){
return true;
}
else if(o == null){
return false;
}
else if(o instanceof Point){
Point p = (Point) o;
return getX() == p.getX() && getY() == p.getY();
}
else{
return false;
}
}
...
}
OOP with Java, David
J. Barnes
Class Inheritance
40
Rules on Overriding
• Return type and arguments must match.
• Sub class version must not be less visible.
• final disregarded in matching arguments.
• Checked exceptions in sub class must be
compatible with those in super class.
– Sub class version may throw none.
OOP with Java, David
J. Barnes
Class Inheritance
41
Method Selection
• Messages always arrive at the outermost
layer for non-private methods.
• The outermost matching method is selected.
– Compilers generate efficient code to handle
selection.
• An inner version may be selected.
OOP with Java, David
J. Barnes
Class Inheritance
42
Selecting the Super Class Version
of a Method
public void method(int arg){
...
// Invoke the closest super class version.
super.method(arg);
...
}
OOP with Java, David
J. Barnes
Class Inheritance
43
Usage of super
• Distinct from usage of super in constructors.
• May be used from anywhere within a
method.
• Only possible to select the nearest version
from an inner layer.
OOP with Java, David
J. Barnes
Class Inheritance
44
Restrictions on Overriding
• Overridden method may not be private.
• Method signatures must have identical name,
return type, argument types.
– Hence, Object argument of equals.
• Sub class version may be more visible.
• Sub class version's exceptions must be a
subset of those thrown by super class version.
OOP with Java, David
J. Barnes
Class Inheritance
45
Styles of Overriding
• Overriding for Breadth.
– Sub class version adds its own behavior.
• Overriding for Chaining.
– Super class version called if necessary.
• Overriding for Restriction.
– Result of super class version modified.
OOP with Java, David
J. Barnes
Class Inheritance
46
Overriding for Breadth
class VariableController extends HeaterController {
public static int DefaultLevel = 16, ...;
...
public void switchOn() throws RuntimeException {
if(!isOn()){
try{
setLevel(DefaultLevel);
}
catch(HeaterLevelException e){
throw new RuntimeException(e.getMessage());
}
}
super.switchOn();
}
}
OOP with Java, David
J. Barnes
Class Inheritance
47
Overriding for Chaining
class MyCommandProcessor extends CommandProcessor {
public boolean process(String command){
if(command.equals(myCommand)){
takeAction();
// We were able to respond.
return true;
}
else{
return super.process(command);
}
}
...
// The command I know how to respond to.
private final String myCommand = "...";
}
OOP with Java, David
J. Barnes
Class Inheritance
48
Overriding for Restriction
public class ChessPiece {
public boolean validMove(Move m, Board b){
if(m.getFrom().equals(m.getTo()))
return false;
else{
ChessPiece target = b.getPieceAt(m.getTo());
if(target == null)
return true;
else if(target.getColor() == getColor())
return false;
else
return true;
}
}
...
}
OOP with Java, David
J. Barnes
Class Inheritance
49
public class Rook extends ChessPiece {
public Rook(int color){
super(color);
}
public boolean validMove(Move m,Board board){
if(!super.validMove(m,board))
return false;
else{
if(m.colDistance() == 0)
return board.clearPath(m);
else if(m.rowDistance() == 0)
return board.clearPath(m);
else
return false;
}
}
...
}
OOP with Java, David
J. Barnes
Class Inheritance
50
Super Class Behavior and
Overriding
• Methods overridden in a sub class will be
invoked from within the super class.
– With the exception of private or static
methods.
• Fields duplicated in a sub class are not
accessed from within the super class.
– Exception through methods overridden in the
sub class, such as accessors and mutators.
OOP with Java, David
J. Barnes
Class Inheritance
51
Final Classes and Methods
• A class defined as final cannot be sub
classed.
– public final class String ...
– Often done to protect complex internal state
representations.
• A method defined as final may not be
overridden.
OOP with Java, David
J. Barnes
Class Inheritance
52