Reading:
This chapter covers the two remaining elements of the object-oriented programming paradigm: inheritance and polymorphism. You have been using both throughout the course, but in this chapter you learn how they work and more importantly, how to implement them.
Read through this review chapter and make sure that you understand the basic version of Simpledraw that it presents in the example revisited section.
To exercise the concepts in this chapter, construct two classes
A
and
B
such that:
B
is a subclass of A
A
implements a method aMethod()
that prints “aMethod” to the console.B
implements a method bMethod()
that prints “bMethod” to the console.
Now, write a console application that creates an object
a
of type
A
and an object
b
of type
B
and verify that
a
can only invoke
aMethod()
but that
b
can invoke both.
When that is running, modify
B
to override the definition of
aMethod()
to print “b's aMethod” and verify that
a
and
b
bind to the correct methods.
Add a new subclass
C
, write a new abstract method
abstractMethod()
in
A
, implement
abstractMethod
in both
B
and
C
as well. Then write a driver method that implements the following method:
public static void printObject(A a) { a.abstractMethod(); }
and calls it using the following lines of code:
printObject(new B()); printObject(new C());
You should get the correct implementation of
abstractMethod()
bound dynamically.
If you’re interested in pursuing a final project along the lines of Simpledraw, download the full application and look through it with an eye to how you might extend it.