Chapter:Inheritance - What is it

From Juneday education
Revision as of 20:11, 9 June 2019 by Rikard (Talk | contribs) (Swedish videos: Couchmode link removed)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Meta information about this chapter

Expand using link to the right to see the full content.

Introduction

Inheritance is a mechanism to create sub types from a more general type. This is similar to the way we think in normal life.

Purpose

Getting familiar with inheritance is important since a lot of existing code uses inheritance (in some way or another) and also the fact that every class we write, or use, extends the class Object - either directly or indirectly.

Goal

The student shall after the completion of all chapters on inheritance:

  • understand the inheritance concept
  • be able to extend an existing class
  • write a class for later extension
  • make it impossible to extend a class
  • override methods in a super class
  • understand and use polymorphism

Concepts

Concepts covered in all chapters on inheritance together, include, but are not limited to:

  • Inheritance - hierarchy of classes
  • All classes extend object
    • You can, but you don't have to, explicitly extend Object
  • Single-rooted hierarchy - a class can extend only one class
  • Overriding a method
  • Reference type versus object type
  • Casting from a type to a subtype
  • instanceof operator
  • basic methods inherited from Object
    • toString()
    • equals(Object)
    • hashCode()
  • Calling a constructor in the superclass
    • implicitly (compiler adds super()
    • explicitly (programmer adds call to one constructor using super(...)
  • Final classes
  • Final methods
    • Methods called from a constructor should be final, if the class can be inherited
  • Abstract classes
    • abstract methods
  • Polymorphism
    • Collections of superclass references
    • Methods accepting arguments of superclass reference type
    • Dynamic binding - the actual object type decides which version of an instance method should run

Instructions to the teacher

Common problems

Spend some time on explaining the difference between the type of a reference variable and the type of an object. Reference type cannot be changed, but the type of the object may vary in runtime, since references can refer to objects of subclass types.

Avoid writing a parameter-less constructor in a superclass just to handle the fact that the compiler might add an implicit call to such a constructor - discuss with the students why it would be a bad idea (often) to allow for a parameter-less constructor, if that means that the object will be partially or completely uninitialized.

Explain that in such cases, it is better to not have a parameter-less constructor, and instead having subclasses constructors' call a superclass constructor (with parameters) explicitly.

Some students confuse inheritance with packages. Explain that you can inherit a class from a different package, but then you either need to fully qualify that class' name, or import the short name. Explain at the same time that this isn't uncommon. In fact, all classes the students have written so far, extend Object (which resides in java.lang) and the students' classes are definitely not placed in java.lang!

Avoid motivating inheritance as the silver bullet for "saving/reusing" code. It isn't. Composition often works as well (or better). A typical indication of careless overuse of inheritance is when you get a class explosion, where new classes inheriting some superclass constantly needs to be added to meet needs.

Full frontal - code example up front!

This code is not supposed to be understood immediately, and is only here as an early code example of some of the syntax involving inheritance.

/* This class is everything an Object is, and then some...
 * To extend a class, is to inherit everything from that
 * class, with the option of adding stuff or changing
 * stuff you "inherit".
 */
public class Customer extends Object {
  
  private String name;
  private String email;

  public Customer(String name, String email) {
    this.name = name;
    this.email = email;
  }

  /* I actually "inherited" this method from Object,
   * but I want to change how the method behaves,
   * so I "override" the method and provide my own
   * implementation of it.
   */
  @Override
  public String toString() {
    return name + " <" + email + ">";
  }
}

What is inheritance

Many object oriented languages have a mechanism for extending existing classes to a subtype. Public (and protected) members of a class will still exist in an extending class, but their implementation may be "overridden" (changed) by the subclass.

To extend (create a subclass, or subtype) a class, you use the extends keyword. There are many examples of this in the Java API (the class library which comes with your Java installation).

Objects of a subtype should have properties and behavior so that they can take the place of any objects of the supertype whithout hurting the (expected) behavior of your system.

An often used example of what could go wrong if this rule is not followed, is if you have a type Rectangle which allows you to change the sides independently from each other, and then create a type Square as a subclass to Rectangle. The Square class will inherit the behavior of changing sides independently from each other, which is not how we think about Squares - Squares sides are equal in length.

If we changed the implementation of the methods for changing one particular side so that it changes both sides, we will break the expected effect for how Rectangles behave!

Note that this problem consists of two parts, first a questionable decision to consider Squares as a subtype of Rectangles, second the decision to make Rectangles mutable. If no rectangles were mutable (they would have only methods to read the sides, not change them), this problem would disappear.

We'll explain inheritance in this chapter by looking at existing inheritance in classes from the Java API (the class library which comes with your Java installation), and by looking at the fact that actually all classes eventually extends the java.lang.Object class.

Chapters on the topic of Inheritance

Videos

Videos for this particular chapter

To date (2018-10-22), there is only one video in English and one video in Swedish. More may be added later.

English videos

Swedish videos

Look ahead! All Videos for all chapters on Inheritance

All videos for all chapters about inheritance (quite a few, quite long screentime):

All English videos for all chapters

All Swedish videos for all chapters

See above for only the videos in this first chapter.

Links

Source code to investigate

Here's some introductory examples - note that these examples just show you basic syntax as a small introduction.

Further reading

These are some recommended readings for those who want to learn more or get a different explanation about inheritance.

Where to go next

Next page contains exercises (if any) for this chapter: Inheritance_-_What_is_it_-_Exercises

« PreviousBook TOCNext »