# 5.1 Inheritance, Superclass, Subclass

Each coding exercise has its own folder. Open its `.java` file and press **Run** to try it. **Run Tests** checks every graded exercise in this lesson at once.

One of the really useful features of Object-Oriented programming is **inheritance**. You may have heard of someone coming into an inheritance, which often means they were left something from a relative who died. Or, you might hear someone say that they have inherited musical ability from a parent. In Java all classes can **inherit** attributes (instance variables) and behaviors (methods) from another class. The class being inherited from is called the **parent class** or **superclass**. The class that is inheriting is called the **child class** or **subclass**.

When one class inherits from another, we can say that it is the *same kind of thing* as the **parent class** (the class it inherits from). For example, a car is a kind of vehicle. This is sometimes called the *is-a* relationship, but more accurately it’s a *is-a kind of* relationship. A motorcycle is another kind of vehicle. All vehicles have a make, model, and year that they were created. All vehicles can go forward, backward, turn left and turn right.

![A UML Class Diagram Showing Inheritance](images/vehicle.png)

*A UML Class Diagram Showing Inheritance*

A **UML (Unified Modeling Language) class diagram** shows classes and the relationships between the classes as seen in Figure 1. An open triangle points to the parent class. The parent class for `Car` and `Motorcycle` is `Vehicle`. The `Vehicle` class has two child classes or subclasses: `Car` and `Motorcycle`.

## Subclass extends Superclass

To make a subclass inherit from a superclass, use the Java keyword **extends** with the superclass name when creating a new subclass as shown below.

```java
public class Car extends Vehicle
public class Motorcycle extends Vehicle
```

> While a person can have two parents, a Java class can only inherit from one parent class. If you leave off the **extends** keyword when you declare a class then the class will inherit from the `Object` class that is already defined in Java.

## Why Use Inheritance?

Inheritance allows you to reuse data and behavior from the parent class. If you notice that several classes share the same data and/or behavior, you can pull that out into a parent class. This is called **generalization**. For example, Customers and Employees are both people so it makes sense use the general Person class as seen below.

Inheritance is also useful for **specialization** which is when you want most of the behavior of a parent class, but want to do at least one thing differently and/or add more data. The example below can also be seen as specialization. An employee is a person but also has a unique id. A customer is a person, but also has a credit card.

![A UML Class Diagram Showing Inheritance](images/person.png)

*A UML Class Diagram Showing Inheritance*

> Check your understanding: If you don’t specify the parent class in a class declaration which of the following is true? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-5-1-inheritance.html#qoo10-1-1

> Check your understanding: If the class Vehicle has the instance fields make and model and the class Car inherits from the class Vehicle, will a car object have a make and model? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-5-1-inheritance.html#qoo10-1-2

> Check your understanding: If I had a class ParkingGarage should it inherit from the class Vehicle? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-5-1-inheritance.html#qoo10-1-3

> Check your understanding: In Java how many parents can a class have? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-5-1-inheritance.html#qoo10-1-4

The Student class can also inherit from the class Person just like Employee and Customer because a Student is a type of Person.

### Exercise 1

What do you need to add to the Student class declaration to make it inherit from type Person? When you fix the code, the **instanceof** operator will return true that Student s is an instance of both the Student and the Person class. What other private instance variables could you add to Person and Student? In which class would you put an address attribute? Where would you put gpa?

> Open the `01-StudentInheritance` folder and edit `Student.java`. Press **Run** to try it; **Run Tests** checks it (2 tests).

## is-a vs. has-a Relationships

Another type of relationship between classes is the **has-a** relationship or **association** relationship. Use this when the object of one class contains a reference to one or more of another class. For example, a course can have many course periods associated with it as shown below. The `1` near the `Course` means that `1` course object is associated with the number shown near the other class. In this case it is `*` which means 0 to many. So one course is associated with 0 to many course periods.

![A UML Class Diagram showing Association](images/assoc.png)

*A UML Class Diagram showing Association*

In the code, the `Course` class **has** an array or ArrayList of `CoursePeriod` objects as an attribute inside it.

```java
public class Course
{
    private ArrayList<CoursePeriod> periodList;
}
```

Alternatively, we could say that a CoursePeriod has a Course attribute inside it to hold the information about the Course. It is up to the programmer how to design these two classes depending on which type of association would be more useful in the program.

```java
public class CoursePeriod
{
    private Course courseInfo;
    private int period;
}
```

Here is another example. Consider the classes Student, Course, and APcourse. An APcourse is a special type of Course. Students are in Courses. What are the relationships between these classes? The UML diagram below shows the inherits (is-a) relationship between Course and APcourse and the associate (has-a) relationship between Course and Students.

![A UML Class Diagram for Student, Course, APcourse](images/APcourseUML.png)

*A UML Class Diagram for Student, Course, APcourse*

We can represent the diagram in Figure 4 in the code below. The Course class has an ArrayList of Student objects in it as the roster attribute. And an APcourse extends Course. What do you think the following code will print out?

### Exercise 2

What do you think the code will print out?

> Open the `02-apclass` folder and run `APcourse.java`. It is an example, so it has no tests.

## is-a Substitution Test

If you aren’t sure if a class should inherit from another class ask yourself if you can substitute the subclass type for the superclass type. For example, if you have a `Book` class and it has a subclass of `ComicBook` does that make sense? Is a comic book a kind of book? Yes, a comic book is a kind of book so inheritance makes sense. If it doesn’t make sense use *association* or the *has-a* relationship instead.

> Only use inheritance when the child class is really a type of the parent class, otherwise use association.

> Check your understanding: An online store is working on an online ordering system for Books and Movies. For each type of Published Material (books and movies) they need to track the id, title, date published, and price. — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-5-1-inheritance.html#qoo_1

> Check your understanding: An online site shows information about Books and Authors. What kind of relationship do these two classes have? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-5-1-inheritance.html#qoo_2

> Check your understanding: What Java keyword is used to set up an inheritance relationship between a subclass and a superclass? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-5-1-inheritance.html#qoo_3

## Coding Challenge: Online Store

Working in pairs or groups, design an online store with classes for Store, ItemForSale, Book, Movie, and Author.

- First, do some research in an online store like Amazon to see what information they store on books, movies, and authors, and what type of information is the same for all items for sale.
- List at least 2 attributes for each class. Which attributes should be in ItemForSale and which in Book, Movie or Author?
- What is the relationship between ItemForSale and Book? between ItemForSale and Movie? between Book and Author? between Store and ItemForSale? You may want to draw UML Class Diagrams for these classes on paper or using an online drawing tool like [app.diagrams.net](https://app.diagrams.net/) or [Creately.com](https://creately.com) (choose UML Class Diagrams, click to connect classes and choose the relationship)
- Use the exercise below to declare each class and specify their relationship to one another with inheritance or association. (Note that usually, each public class would be in a separate file, but since we only have 1 file in this exercise, we only make 1 class public). Only put in the instance variables for each class. We will learn how to make constructors and methods in the next lessons.

### Exercise 3

Declare at least 2 instance variables for each of the classes below. Create an inheritance or association relationship for some of them.

> Open the `03-challenge-inheritance-online-store` folder and edit `Store.java`. Press **Run** to try it; **Run Tests** checks it (5 tests).

## Summary

- A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a **superclass**.
- Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without repeating these in the code.
- The keyword **extends** is used to establish an **inheritance** relationship between a **subclass** and a **superclass**. A class can extend only one superclass.
- Extending a subclass from a superclass creates an **is-a relationship** from the subclass to the superclass.
