Inheritance in Java Programming
Inheritance
- Access Attributes (from Horton's
Beginning Java 2, pp. 213, 214, 238)
- Animals Inheritance examples:
- version 1 (handout (doc), or directory): Basic inheritance using extends, no-args constructor in
superclass needed, overloaded constructors. Using classes Animal.java, Dog.java, Driver.java
- version 2 (handout (doc) or directory): Chaining constructors using this, invoking superclass constructor
using super,
for Animal2.java, Dog2.java, Driver2.java
- Overriding superclass toString method: access specifier (i.e.
public) for the overriding class may not be more restrictive
than that of the superclass.
- Cannot string more than one super together. (i.e. super.super.toString()
is invalid.)
- version 3 ( handout (doc) or directory): Polymorphism, where the type of an object is determined at runtime
and changes the behavior of the program. 3 Different animals all have
the sound method implemented.
Animal3.java, Cat.java, Dog3.java, Dolphin.java, Poodle.java, Dolphin.java, and Driver3.java
For polymorphism to work (e.g. objects
of type Animal all call the correct class corresponding to the
actual type of each one) the following must be true:
- The method call (e.g. sound() ) must be through an object
of the base class (e.g. Animal).
- The method in the derived class must have the same argument signature
and return type as that in the base class.
- The method in the derived class must have an access specifier no
more restrictive than that of the base class
- version
#4: abstract classes.
Animal4.java, Cat4.java, Dog4.java, Driver4.java
- A class with one or more abstract methods is itself an abstract
class, which cannot be instantiated. It is useful for organizing
subclasses.
- An abstract class method declaration ends with a semi-colon,
e.g. method sound() in class Animal4.
- Another Inheritance Example: Subclassing
(doc file, from Liskov), and the corrresponding class handout
for the Account class (doc file)
- All user-defined classes themselves are actually subclasses of super-class
Object. Class Object has some public methods which we commonly
override:
- toString() - This gives us a representation of an object as a String
- equals() - This compares the calling object with the object sent as
a parameter, returning true if they are actually the same object, not
just containing the same values.
- getClass() - This returns an object of type Class that identifies
the class of the current object.
- We could use this, for instance, if we want to print only elements
of class Dog.
- This also illustrates using qualified names to access methods outside
the current package.
- hashCode() - This calculates an integer hash code value for an object
and is used for storing objects in hash tables.