(syllabus and calendar)

Ch. 7 Inheritance
pp. 251-300


week7examples.zip

Session 7


Inheritance is a Construction


Practice Quiz (with answers)


Inheritance and the keyword extends

Using super to access superclass members

super() to call constructor of the superclass

multilevel hierarchy: C extends B, B extends A

constructors and private members are not inherited

Non-default constructors

this and super - review

Enforcing inheritence by a call to the constructor of the superclass

Recreating super() if the default constructor is removed

Superclass reference to subclass object


Overriding Methods


Dynamic Method Dispatch

Array with Dynamic Types


Abstract Class and method overriding


final keyword has three levels (variable, method, class)

Object class


Quiz

Inheritance is a Construction


Let's predict the output of this program.

class A {
  A() {
  System.out.println("Constructing A.");
  }
}

// Create a subclass by extending class A.
class B extends A {
  B() {
  System.out.println("Constructing B.");
  }
}

// Create another subclass by extending B.
class C extends B {
  C() {
  System.out.println("Constructing C.");
  }
}

class OrderOfConstruction {
  public static void main(String args[]) {
    C c = new C();
  }
}

Practice Quiz with Answers to help you prepare for the Quiz that does not show the answers

  1. Class B extends A. Both have a method called makeApplesauce. In B, this method takes an integer argument. In A, this method takes a double argument. Is the method overloaded, overridden, both, or neither? This concept implemented with a slightly different set of signatures:


    Overloaded even though it is in a subclass. The method that overrides another method must have exactly the same signature as the method it overrides.

     
  2. When I explicitly call the constructor of class B, what is implicitly called?

    The constructor of the superclass.


     
  3. Referring to the answer of Question 2, why is this the way it is?

    To enforce inheritance. For example, to initialize any inherited instance variables.


     
  4. Should the common logic be in the superclass or in the subclasses that extend the superclass?
    (To maximize code reuse, the common logic should be in the superclass.)
     
  5. What does the word final mean for the following?:
  1. In what sense is an abstract class abstract?

    At least one method is not implemented (no code block) and consists solely of a statement that is a signature declaration.
     
  2. In what sense can an abstract class be something other than fully abstract?

    An abstract class can have one or more method implementations (code blocks, whether empty or not). We will see next week that an Interface does not have any method implementation whatsoever within the interface.
     
  3. Does a subclass inherit the constructors of its superclass?

    No, but it can call any constructor that belongs to its immediate superclass with super(), super("a string"), super(17), or similar.
     
  4. Using super(), what can the current class gain access to?

    The default constructor of the immediate superclass (or the custom constructor that has the matching signature of 0 parameters).
     
  5. Does the Java compiler allow access to the grandparent class using the following syntax?: super.super   
    No.

Inheritance - keyword extends - extending a class (subclassing)

A subclass is an extension or specialization. For example, an instance of BrainSurgeon of a specialized class of Doctor.

The keyword extends allows you to declare that a class is a specialization (subclass) of another class, its superclass. For example, a medical doctor might consider herself or himself to be a special kind of person.

class Person
{
   String name = "";
   int ssn = 0;
   Person(String name)
   {
      this.name = name;
   }
   Person(int ssn)
   {
      this.ssn = ssn;
   }
}
class Doctor extends Person
{
   Doctor(String name)
  {
      super(name);
   }

   Doctor(int socialSecurityNumber)
   {
      super(socialSecurityNumber);
   }
}
class PersonDemo
{
   public static void main(String[] args)
   {
      Doctor drwatson = new Doctor("Watson");
      drwatson.ssn = 001331234;
      System.out.println(drwatson.name + ": " + drwatson.ssn);

      Doctor drpepper = new Doctor(823556789);
      drpepper.name = "Soft Drink";
      System.out.println(drpepper.name + ": " + drpepper.ssn);
   }
}


We have seen multiple classes in the same compilation unit (file). Any number of class can be in the same java file, but it is generally a good idea to have only one. If the file has the main class, the file name must match the class with main.

Note: We can also put each class in each own file, as long as the class with main can see the other classes. Currently, we use the default package, so any class in the current directory is visible.

When you compile the class with main, the compiler also compiles any classes that main references.

Here, when we compile the class with main, we generate three class files. In our domain logic, the Triangle and the Rectangle classes are specializations of TwoDShape. The subclasses have special ways of calculating area.

Subclasses inherit from their single-inheritance superclass. The superclass encapsulates the general logic. The subclass adds specialization. The inheritance tree descends from the general (Object) to the specific (TwoDShape), to the even more specific (Triangle and Square). Thus, we can re-use shared, general code and only have to write the specialized differences (the deltas) on the subclasses.

Info for t1:
Triangle is isosceles
Width and height are 4.0 and 4.0
Area is 8.0

Info for t2:
Triangle is right
Width and height are 8.0 and 12.0
Area is 48.0

Info for r1:
Area is 9.0 and is this rectangle a square?: true

Constructors and private members are not inherited

The subclass does NOT inherit the superclass constructors, although can call them using
super(constructorSignature)

In the following example, Line 29 must be commented out, even though lines 23 and 14 are allowed. This means that the subclass did not inherit the constructor that takes a boolean argument.

The subclass does NOT have access to the superclasses' private members

Otherwise the keyword private would not prevent another programmer from subclassing a class to gain access to the private members.


(A biblical analogy might be Genesis 9:20, where Noah's son, Ham, is not allowed to see the private members of his father.

As punishment therefore, Noah makes Ham inherit a curse. http://en.wikipedia.org/wiki/Curse_of_Ham))

In this example, the width and height of the private member is not visible to the children classes.

Info for t1:
Triangle is isosceles
Width and height are 4.0 and 4.0
Area is 8.0

Info for t2:
Triangle is right
Width and height are 8.0 and 12.0
Area is 48.0

Inheritance and Non-default Constructors

Now let's set values with the constructor of the subclass instead of doing so in the class with main.

Info for t1:
Triangle is isosceles
Width and height are 4.0 and 4.0
Area is 8.0

Info for t2:
Triangle is right
Width and height are 8.0 and 12.0
Area is 48.0


Here, we add a constructor to the superclass, which can update functionality that subclasses do not know about.
Notes:

The following examples uses accessor methods, which are also called "getter" methods.

Info for t1:
Triangle is isosceles
Width and height are 4.0 and 4.0
Area is 8.0

Info for t2:
Triangle is right
Width and height are 8.0 and 12.0
Area is 48.0


Using super to access superclass members

If your method hides one of its superclass's member variables (by having the same name), your method can refer to the hidden variable through the use of the super keyword. Similarly, if your method overrides one of its superclass's methods (by having the same name and signature), your method can invoke the superclass version of the overridden method through the use of the super keyword. (Compare to how a local variable name can hide a instance variable name.)

In which line does the subclass hide a variable of the superclass?
In which line does the subclass override a method of the superclass? Do both versions of the overridden method have the same signature?

Access a constructor of the superclass

Here, the subclass makes separate calls to each of the superclass constructors. The syntax for calling a superclass constructor is super(parameter_list). We care about the parameter list, the signature, when calling a constructor because a constructor, like a method, can be overloaded.

Info for t1:
Triangle is right
Width and height are 8.0 and 12.0
Area is 48.0

Info for t2:
Triangle is right
Width and height are 8.0 and 12.0
Area is 48.0

Info for t3:
Triangle is isosceles
Width and height are 4.0 and 4.0
Area is 8.0

Access an instance variable of the superclass

Using super to access an instance variable of the superclass. Remember, the superclass does not know about its subclasses. Therefore, the changes made on the inherited member do not affect the copy of that member in the superclass. Here, we use super.superclass_member in a manner analogous to using this.class_member, that is, to unhide a instance variable that has been hidden by a local variable. Otherwise, from B's point of view, the variable i refers to this.i, that is, B's version of i.

Review: Access an constructor of the superclass

Let's review with a different class hierarchy.

Semi can carry 44000 pounds.
To go 252 miles semi needs 36.0 gallons of fuel.

Pickup can carry 2000 pounds.
To go 252 miles pickup needs 16.8 gallons of fuel.


Multilevel hierarchy

There is no limit to the number of levels in a hierarchy of inheritance. (Japheth to Jefferson Davis, or Ham to Frederick Douglas, might be 150 generations.)

Here, we extend TwoDShape with Triangle, and also design a specialize triangle, ColorTriangle. This is for purposes of illustration because color should be an attribute, property, or field of Triangle or TwoDShape.

Info for t1:
Triangle is right
Width and height are 8.0 and 12.0
Color is Blue
Area is 48.0

Info for t2:
Triangle is isosceles
Width and height are 2.0 and 2.0
Color is Red
Area is 2.0


this and super - review

What is the purpose of the keyword this in lines 16-22? Does this.hue unhide field that would otherwise be hidden by the formal parameter, hue?


Enforcing Inheritance: superclass constructor called implicitly

The order of construction is determined by derivation. Java enforces that the superclass has priority.

If the superclass has instance variables that the constructor initializes, we can be certain that the subclass that inherits these instance variables will inherit them with the proper initialization.

This example use this.methodName() and super.methodName() to make use of method overrides.


Recreating super() if the default constructor is removed


Reference of type superclass to subclass object

The superclass X does not know about Y's field (instance variable) b. However, a subclass can assign a reference of its superclass. In other words, a superclass reference can refer to a subclass object. Can  a subclass reference refer to a superclass object? No. Is this similar to the implicit cast of a primitive to a widening type?

The following program has a subclass that passes an object of its type to the superclass constructor. This supports basic code reuse. Insofar as the subclass extends the superclass, the subclass is of the type of the superclass. (A BrainSurgeon is also a Doctor is also a Person.) Is there a relationship between lines 64 and 22?

Info for t1:
Triangle is right
Width and height are 8.0 and 12.0
Area is 48.0

Info for t2:
Triangle is right
Width and height are 8.0 and 12.0
Area is 48.0


Book example of superclass references and subclass objects (p. 274)

A reference of the superclass can be assigned to a reference of a subclass (line 40), but it has access only to the members that the superclass knows about. In this case, the superclass Book does not know about the subclass having a specialized field.

The output is:

constructor for the superclass that takes no arg
constructor for the superclass takes a book object
superclass book title
constructor for the superclass that takes no arg
superclass book title
subclass book title
assigning a superclass reference variable to a subclass object reference
Although the reference is of type Book, the object is of type MusicBook: MusicBo
ok@19821f
inherited methods and fields remain available:
superclass book title
However, the subclass methods and fields are NOT available to a reference of the
superclass type



Method Overriding

Overloading is HORIZONTAL typically within the same class, and means different signatures for the same method name.
    myOverloadedMethod(int i)  versus  myOverloadedMethod(int i, int j) versus myOverloadedMethod(int i, double j)
 

O
v
e
r
r
i
d
e
Overriding is VERTICAL - how a subclass customizes the behavior it inherits, and means the same method signature but different implementation code.


All mammal have an eat() method. The horse overrides this inherited method by chomping on dry hay with its mouth. The cowboy overrides the eat method by eating with campfire beans with a fork.

Chomping on dry hay and eating campfire beans with the fork are specializations of the general method of eating. The Horse class eat() method overrides the Mammal class eat() method, just as the Cowboy class eat() method overrides the Mammal class eat() method.

These photos show the Cowboy and the Horse can both be viewed are overriding a Mammal.

Whereas method overloading is within the same class (horizontal), method overriding means the subclass method overrides the superclass method (vertical) it inherits.
Method overloading is polymorphism; method overriding is an exception to inheritance.

Suppose you the programmer who must write a subclass for a superclass. You see that one of the methods the subclass inherits from the superclass must have different behavior. A use case (http://en.wikipedia.org/wiki/Use_case) might be the calculateTax() method, which is different depending on the local nation, state, county, and/or city. Some localities have only national tax, others have both federal and state, still others have federal, state, and city.

The following example illustrates overriding the inherited show() method.

The following demonstrates a method overloading. Do the signatures of the show method match?

To override a method, the subclass version must have the identical signature as the superclass version.
Otherwise, we have
overloading that happens to occur in the class that inherited the method.
So, in a sense, overloading, which is normally horizontal, can be vertical: the subclass can introduce a different signature to the method it inherits.
Overriding is always vertical.


Dynamic Method Dispatch Depends on Reference Type

At runtime, Java can determine which version of method to run according to which object that method is on.


Array of Dynamic Types

Method overriding can be used with the best practice of moving common logic up to the superclass. Shapes have areas, but each subclass can override the area method for its special circumstances. What are the contents of the array created in line 127? Does it violate the rule that an array must collect objects of solely ONE type?

object is triangle
Area is 48.0

object is rectangle
Area is 100.0

object is rectangle
Area is 40.0

object is triangle
Area is 24.5

object is generic
area() must be overridden
Area is 0.0


Abstract Class and Method Overriding

The follow example prescribes that subclasses shall implement a getMaximumSpeed method, which the ModelT class does. The Tbird subclass of ModelT overrides that method, and uses the keywords super and this to access both the overridden version and the override version.

An abstract class is similar to an ordinary class but functions as a template for creating subclasses. For example, the abstract class, java.io.InputStream http://java.sun.com/javase/6/docs/api/java/io/InputStream.html provides implementation methods for managing the bytes in an stream, such as read(byte[]  b), mark(int readlimit), reset(), skip(long n), and close(). Therefore, subclasses, such as AudioInputStream and FileInputStream have the choice to reuse the implementation or overwrite it.

Can I use the keyword abstract for a class that lacks an abstract method?

Let us prove that an abstract class cannot be instantiated. Will such code even compile?

A method can be abstract if it does not contain an implementation block, and if a method is abstract, the class must be declared abstract.

An abstract class cannot be instantiated. Instead, a subclass must fulfill the obligation to provide implementation, and only such a subclass can be instantiated:

Returning to the dynamic shapes solution, the DynShapes program included line 47, which is a hack insofar as:

Instead, we should declare the superclass to be an abstract class.

Every subclass that extends an abstract class inherits an obligation (we say a contract) to implement the abstract methods of the superclass.

This way, appropriate code is written where it is needed, and no code must be ignored.

An abstract class is a common solution when we know the subclass is likely to override the superclass.

In general, provide an abstract class when you can provide only SOME of the implementation, and other developers will later provide additional customization of your code. Use cases (http://en.wikipedia.org/wiki/Use_case) might be:

An abstract class cannot be instantiated, so a subclass does the instantiation. An abstract class can provide partial implementation. A non-abstract subclass typically overrides one or more methods of the abstract superclass. The non-abstract subclass can be instantiated.

Note:

object is triangle
Area is 48.0

object is rectangle
Area is 100.0

object is rectangle
Area is 40.0

object is triangle
Area is 24.5


Lab Exercise (if time permits)

Write an abstract class called Animal that has at least one abstract method and one non-abstract method. Extend the abstract class in a non-abstract subclass that overrides the abstract method it inherits by implementing the abstract method. Your implementation must not be empty  { }. In other words, provide code in the implementation code block, such as an indicative println method. Also override a non-abstract  method it inherits.

Overriding: see http://write-technical.com/126581/session7/index.htm#override
and http://java.sun.com/docs/books/tutorial/java/IandI/override.html

Abstract class: see See http://write-technical.com/126581/session7/index.htm#Abstract%20Class


Avoiding Inheritance with the keyword final (p. 295)

The keyword final has three levels of use in Java: variable, method, class.

Final can be used with a variable to make it a constant:

final int BOILING_POINT = 100;

The following example uses a standard convention for error messages. The API could advise user programmers to use the string  constants. The associated integers can be changed between product releases without breaking code.

A method can be declared final. That means it cannot be overridden.

A class be declared final. That means that not only are its methods final, but the class cannot be extended by a subclass or even inherited by a subclass. A final class is one way to provide logic that is uniform throughout a large project involving many programmers.


How can I create a class that is guaranteed to have only one instance? Such a class/object is known as a singleton.  http://www.javaranch.com/newsletter/July2003/SaloonQnAOfTheMonth.html

An example of the singleton design pattern:

Final Variables

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/finalVariables.html

Constant

A constant variable is a variable which is assigned a value once and cannot be changed afterward (during execution of the program). The compiler optimizes a constant for memory storage and performance.

Examples of constants

You can declare a variable in any scope to be final (in the glossary). The value of a final variable cannot change after it has been initialized. Such variables are similar to constants in other programming languages.

To declare a final variable, use the final keyword in the variable declaration before the type:

final int aFinalVar = 0;

The previous statement declares a final variable and initializes it, all at once. Subsequent attempts to assign a value to aFinalVar result in a compiler error. You may, if necessary, defer initialization of a final local variable by declaring the local variable and initializing it later:

final int blankfinal;
. . .
blankfinal = 0;

A final local variable that has been declared but not yet initialized is called a blank final.

A common use case for a final variable is a set of constants for error messages.

http://java.sun.com/docs/books/tutorial/java/javaOO/final.html


Object class and an array of type Object

An array of objects can store any type of Object, be it an instance of String or any other subclass of java.lang.Object. An abstract class cannot be instantiated, so it cannot have objects to store in an array of objects. However, a subclass of an abstract class that, as subclass, is NOT abstract, can be the type of object stored in an object array.

When you are at the Object level, you can only see that methods that belong to that class, such as toString().
See http://java.sun.com/javase/6/docs/api/java/lang/Object.html. The Object class does not know anything about what a subclass might or might not have. If you want to access the class members of a subclass, you have to work with that subclass. To explicitly cast a object that is a subclass of java.lang.Object to be considered as of type  java.lang.Object, you would use this syntax: (Object) myObject;

The Output is:

Volume is 3000.0
myStringArray One and Two are...StringOne and StringTwo and mybox.toString(): Bo
x@82ba41
length of String array: 4
myObjectArray has the following: StringOne and StringTwo and Box@82ba41
length of object array: 4



Quiz: Session 7

  1. Class B extends A. Both have a method called makeApplesauce. In B, this method takes an integer argument. In A, this method takes a double argument. Is the method overloaded, overridden, both, or neither?

  2. If the method named calculate() overrides a method named calculate(), is the overridden method in the superclass or in the subclass?

  3. Suppose class B extends class A. When I explicitly call the constructor of class B, what is implicitly called?

  4. Referring to the answer of the previous question, is this related to polymorphism or inheritence?

  5. Should the common logic be in the superclass or in the subclasses that extend the superclass?

  6. What does the word final mean for the following?:

  1. Can an abstract class have methods that are NOT implemented with a code block?

  2. Can an abstract class have methods that ARE implemented with a code block?

  3. Does a subclass inherit the constructors of its superclass such that it can use their signatures at the subclass level without defining any subclass constructors?

  4. Using super("hello", 3.3), what might a class be calling?

  5. Does Java allow the syntax of super.super to access the superclass of the superclass?

  6. Can an array of type String store objects of type Object, provided a cast to (Object) is used?

  7. Can an object be cast to a type of its subclass?

  8. An abstract class cannot be instantiated, but is it possible to have an array of objects, each of which is an object of a class that extends an abstract class? Hint: See Object class and an array of type Object