Extending Classes

It is a common case in Java programming to have many classes that share core features. For efficiency, Java provides a way for classes that share these common features to be written quickly and efficiently without rewriting all of the duplicate code.

We must first represent the “common ground.” For this example, we’ll take a Dog class and a Cat class. The common ground here could be an Animal class that includes instance variables like color and isPet.

Define this class as you normally would, only including instance variables that both Dogs and Cats have in common, as shown below.

public class Animal
{
  private String myName;
  private String myColor;

  public Animal( String name, String color )
  {
    myName = name;
    myColor = color;
  }

  public String getName()
  {
    return myName;
  }

  public int getColor()
  {
    return myColor;
  }
}

Note: for more information on classes, refer to my notes on OOP here.

Now is when it changes. Let’s build the Dog class. I’ll explain what everything new in the class means below it.

public class Dog extends Animal
{
  private String myFavoriteToy;

  public Dog ( String name, String color, String favoriteToy )
  {
    super( name, color );
    myFavoriteToy = favoriteToy;
  }

  public String getFavoriteToy()
  {
    return myFavoriteToy;
  }
}

Changes from normal class declarations:

extends | required keyword that tells the class written before it (called the child class or subclass) to extend its definition to match the class after it (called the parent class or superclass).

super() | constructor for the parent class built into the child class. This allows the child class to use code in the parent class. It must be the first line of the child class constructor.

Instance variables do not have to be declared or have accessor/modifier methods in the child class if they are already present in the parent class.

A child class can also be a parent class to another child.

Phrasing:

The Dog class extends the Animal class

The Animal class is the superclass of the Dog class

The Dog class is the subclass of the Animal class

The Dog class is derived from the Animal class

The Dog class inherits the public methods of the Animal class