The inheritance hierarchy
o No class can have more than one parent.
o If a class has no parent declared, it is a child of class Object.
An exception: class Object has no parent.
o So all classes form a tree, with Object at the root.
o This tree is called the inheritance hierarchy.
o Class Object makes sure that every class inherits methods like equals and toString
A few quick points about inheritance
o Super refers to the part of the object that is defined by its parent class
o You can call a constructor in the parent class by calling super(arguments)
If you don’t do this explicity, it will happen implicitly (and w/ no arguments as the very first thing)
o A subclass can add new data members or methods to those it inherits
o It can also reuse a name already in use for an inherited data member or method
There are subtleites we’ll discuss next week
o Child classes don’t have access to private members of their parent. We’ll say more about accessibility next week
Constructors and inheritance
o When you say new, the appropriate constructor is called (based on the number and type of arguments)
o If the first step is super(arguments)
the appropriate constructor in the parent class is called
otherwise, the no-argument constructor in the parent is called
o Net effect on order if, say, A is parent of B is parent of C
o Which constructor should do what?
Good practice: initialize only your own variables, and count on ancestors to take care of theirs
o If you don’t define any constructors for your class, the compiler will define one with no arguments and an empty body
This is useful, since that your no-arg constructor will be called if a child class doesn’t explicitly call one of your constructors
o But if you do define any constructors, the compiler won’t define a no-arg constructor for you
o A child class may run into problems.
Example: classes Top and Bot
o If Top has no constructors at all and Bot doesn't say super
Then Bot's constructor calls the default no-arg constructor in Top
o If we add a no-arg constructor to Top. We can see it being called;
notice the calls happen bottom-up; execution order is top-down
o If we have Bot explicitly call it the constructor in Top. This makes no difference
o If Top has just a one-arg constructor and Bot either
(a) explicitly calls the no-arg or
(b) doesn't say super
Then there is no default no-arg constructor, and Bot won't compile because there is no no-arg constructor to call
o If Top has just a one-arg constructor and Bot calls it
Then there is no default no-arg constructor and it doesn't matte