Inheritance

Implementing Inheritance

🙋 Need help? Ask an expert now!

Object oriented languages like Java have a feature called "inheritance" which allow programmers to define new classes based on an existing class. Instead of starting from nothing, we can build upon a previously existing class, or a "superclass", and add more variables and methods to the superclass. The program below shows a simple implementation of inheritance.

EnglishGreeting.java
package exlcode;

public class EnglishGreeting extends Greeting {

  public void print() {
    // the InheritanceTestTwo class inherits variables
    // and methods from InheritanceTestOne
    System.out.println(exampleVariableOne + " subclass");
    printer();
  }
}
Greeting.java
package exlcode;

public class Greeting {

  public String exampleVariableOne = "Hello World!";

  public void printer() {
    System.out.println(exampleVariableOne + " superclass");
  }
}
InheritanceExample.java
package exlcode;

public class InheritanceExample {

  public static void main(String[] args) {
    EnglishGreeting englishGreeting = new EnglishGreeting();
    englishGreeting.print();
  }
}

We classify the classes into "superclass" and "subclass". Let's use the "is-a" relational comparison to show the relationship between the super and the sub class like this; for the program above, EnglishGreeting is-a Greeting.

The subclass is used to construct objects that look like the superclass's objects, but with added features such as extra variables and methods. In order for the subclass to use the public methods and variables, Java reserved word extends is used when implementing inheritance code.

By having a superclass with general methods and variables that apply to all the subclasses, you can save a lot of coding time at the individual subclass level.

You can create objects using the syntax SuperClass objectname = new SubClass(); because the subclass extends from a superclass and "is-a" superclass. Switching the position of the superclass and the subclass here will throw an error.

Application Question

A bookstore is working on an on-line ordering system. For each type of published material (books, movies, audio tapes) they need to track the id, title, author(s), date published, and price. Which of the following would be the best design?