% cd % cd cs21 % mkdir week10 % cd week10 % pwd % cp ~newhall/public/cs21/week10/* .
class hierarchy:
Top
---------------
| Data: t
| Methods: getT
---------------
|
Middle
---------------
| Data: m Middle inherits t and getT
| Methods: getM
---------------
|
Bottom
---------------
| Data: b Bottom inherits t and m, getM and getT
| Methods: getB
---------------
This example illustrates some important features of inheritance in Java:
1. When you create an instance of class, Java automatically invokes
the constructor of the parent class first to initialize its part
of the object
2. If a constructor does not initialize the data members of a class,
Java will automatically initialize them to default values, which
are: zero for numbers, false for booleans, and null for Objects
such as Strings.
3. You can use the "instanceof" operator to determine if a given
object is an instance of a particular class.
Let's add constructors that take params to Middle and Bottom, and then
construct a new Bottom object by using invoking the non-default constructors
Person all classes implement Comparable<Person>
/ \ (inherited from the Person class)
/ \
Student2 Faculty
/ \
/ \
TenureTrack Visiting
/
/
DeptChair
Notice that the toString method is overridden in the derived classes.
See how super is used to get a String representation of the private data
members that are inherited by the derived classes. Also, note that each
class implements the Comparable interface, and that all the derived classes
do not override the Person class's compareTo method.
(a) examine RunStudentFaculty.java file. Notice how a Person object
reference can refer to a Person, or a Student2, or a Faculty, or a ...
object. Compile and run the program.
(b) to the Visiting class, change the toString method to return
a string of the form:
name
age
Visiting Professor
department
start date - current date
then re-compile and run