(syllabus and calendar)

Ch. 7 Inheritance
pp. 251-300


examples7.zip

 

Session 7


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

Non-default Constructors

this and super - review

Enforcing Inheritence by Call to Superconstructor

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

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?

    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.

    Let's see this with a slightly different signature difference:

     
  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.
     
  3. Does a subclass inherit the constructors of its superclass?

    No, but it can call the constructor that belongs to its immediate superclass.
     
  4. Using super(), what can the current class gain access to?

    The constructor of the immediate superclass.
     
  5. Java does not allow the syntax of super.super   
    No.

Extending a class (subclassing)

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. The next time you go to a doctor, tell the doctor that, according to Java, she or he is a subclass 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);
   }
}


Inheritance

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

Two notes about inheritence:

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).

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.


Reference of type superclass to subclass object

The superclass X does not know about Y's 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. 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.

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.
(whereas the horse eats only with its mouth, the cowboy overrides that eat method by eating with a fork and knife in conjunction with his mouth)

In this sense, eating with knife and fork would be a specialization of the general eating with the mouth, so Cowboy is a subclass of 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.

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 occurs 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 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

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.

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 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. Instead, 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. 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

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 doesn't 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. When I explicitly call the constructor of class B, what is implicitly called?

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

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

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

  1. In what sense is an abstract class abstract?

  2. In what sense can an abstract class be something other than fully abstract?

  3. Does a subclass inherit the constructors of its superclass?

  4. Using super(), what can the current class gain access to?

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