CS51 - Fall 2009 - Lecture 18
in the real world we often describe objects as being similar to something else and then discuss the differences (eg. a strobe light is a light that flashes). inheritance lets us do the same in java.
basics of inheritance
when a class
extends
another class it becomes a subclass of that other class. alternatively, the other class is a superclass of the new class. The subclass inherits everything defined in the superclass.
think about using inheritance when several classes have similar behaviors.
for an example, see
FallingObjects
notice how the constructor for the
Hail
and
FallingLeaf
classes works.
can also override methods in the superclass
for an example, see
FallingObjectsWithTomatoRun
notice how
super.run()
is used in the
run()
method in the
Tomato
class.
we can also split up the
run()
method in
FallingObject
class, which makes it easier to do things such as:
FallingObjectsWithCows
assignment statements with classes and superclasses
errors
using
instanceof