10 ch11 Inheritance
10 ch11 Inheritance
Chapter 11
Spring 2007
CS 101
Aaron Bloomfield
1
This section is not required material!!!!
A note about inheritance…
It’s not normally covered in 101
It will be gone over in more detail in CS 201
2
Motivation
Consider a transportation computer game
Different types of vehicles:
Planes
Jets, helicopters, space shuttle
Automobiles
Cars, trucks, motorcycles
Trains
Diesel, electric, monorail
Ships
…
4
Motivation
Sample code for the types of planes:
fly()
takeOff()
land()
setAltitude()
setPitch()
Note that a lot of this code is common to all types of planes
They have a lot in common!
It would be a waste to have to write separate fly()
methods for each plane type
What if you then have to change one – you would then
have to change dozens of methods
5
Motivation
Indeed, all vehicles will have similar methods:
move()
getLocation()
setSpeed()
isBroken()
Provides: Provides:
fly() move()
takeOff() getLocation()
land() setSpeed()
setAltitude() Vehicle
isBroken()
setPitch()
The “child” class (or subclass) will inherit the methods (etc.)
from the “parent” class (or superclass)
8
Inheritance code
class Vehicle {
...
}
9
About extends
If class A extends class B
Then class A is the subclass of B
Class B is the superclass of class A
A “is a” B
A has (almost) all the methods and variables that B has
10
Object-oriented terminology
In object-oriented programming languages, a class created
by extending another class is called a subclass
The class used for the basis is called the superclass
Alternative terminology
The superclass is also referred to as the base class
The subclass is also referred to as the derived class
11
10 dimensions
Disclaimer: it doesn’t have much scientific
validity
http://tenthdimension.com/
12
Another example
Consider shapes in a graphics program
Shape class
Circle class
Cube class
Dodecahedron class
14
Inheritance
Organizes objects in a top-down fashion from most general to
least general
15
Packages
Allow definitions to be collected together into a single entity—
a package
default
private
17
Java’s Mother-of-all-objects—Class Object
18
Thus, everything extends Object
Either directly or indirectly
19
More about clone()
It’s protected in class Object
Which means that a Circle class also has a protected
version
Recall that protected means that code outside the Circle
class can NOT call it
20
A note about equals()
Why does the equals() method always have to have the
following prototype:
boolean equals(Object obj)
Many other class in the Java SDK require the use of equals()
Such as the Vector class
24