Chapter 5 - Java for Beginners Course

Inheritance Basics

As mentioned in Chapter 1, Java is class-based and object-oriented, and as such we need to understand some OOP features that are supported by the Java language and that will become prevalent as we progress on the course. The first of the concepts we’ll cover is Inheritance.

This feature adds the possibility of inheriting state and behavior across different classes and of defining a type hierarchy across the class structure of our application.

In this sense, a class can be a parent class (a.k.a base class or superclass) that inherits its state and behavior to its children classes (a.k.a subclasses).

Following the Airplane example from Chapter 1, let’s assume that we need to have different types of planes in our code.

For the purpose of the example, we can think about a MilitaryAirplane and a CommercialAirplane.

Both of them share the same common concepts defined in our Airplane class (the common state and behavior between the two). For example, both types of planes can takeOff and land. But they can also have additional features that make them different.

The extends keyword

In order to define a relationship between two classes we make use of the extends keyword in Java in the class declaration, with the following syntax:

public class SubClass extends SuperClass {
	//...
}

Following the example above, let’s assume we have our Airplane class:

public class Airplane {
    //...
}

And also add a CommercialAirplane class to our code:

public class CommercialAirplane {

    private int passengersOnBoard;

    public void boardPassenger() {
        passengersOnBoard++;
    }

    public int getPassengersOnBoard() {
        return passengersOnBoard;
    }

}

In its current form, the CommercialAirplane class adds some state and behaviour that doesn’t exist in the Airplane class (like boardPassenger()). However, we haven’t yet defined any relationship between the two classes. From Java’s point of view both classes aren’t related to one another.

By making use of the extends keyword we define the relationship we want between our 2 classes as follows:

public class CommercialAirplane extends Airplane {
	//...
}
All classes in Java have one super-class. If a super-class isn’t defined explicitly, then the java.lang.Object or Object class is used by default.

This means that now our CommercialAirplane has the same characteristics as an Airplane and, we can now say that a CommercialAirplane is-a-type-of Airplane.

Let’s give this a go:

In the Java example project run the JavaExtendsApp application.
CommercialAirplane commercialAirplane = new CommercialAirplane();

// we can invoke methods defined in the CommercialAirplane class as expected
commercialAirplane.boardPassenger();
System.out.println("Number of passengers on board: " + commercialAirplane.getPassengersOnBoard());

// as the class inherits from Airplane, we can also invoke methods defined in the Airplane class
commercialAirplane.setManufacturer("Airbus");
commercialAirplane.setNumberOfSeats(300);
commercialAirplane.takeOff();
commercialAirplane.retractLandingGear();
commercialAirplane.printDetails();

Output:

Number of passengers on board: 1
manufacturer=Airbus, numberOfSeats=300, landed=false, gearDeployed=false
Try removing the extends Airplane from the class declaration and see what compilation errors are shown. You should see that all the method calls in the JavaExtendsApp class that come from the Airplane class will be highlighted as errors.
A class can have an unlimited number of sub-classes that inherit from it.
Java’s Object class is the root class of all classes in Java.
Code in GitHub

Get the code for this tutorial using the links below.

Project Repo
Download code for this step
Main class for this step
Dependencies

This is a list of recommended tutorials or courses that might be useful before starting this one.

Contents
Welcome to the Course!
Course Introduction
Chapter 1 - Building Blocks
Quick introduction to Java Variables Classes And Objects Class Example - Defining a class Object Examples - Creating instances Java Application Example - Running our first app Accessing class members - The dot operator Packages - Organizing the code
Chapter 2 - Primitives and Operators
Primitives Arithmetic Operators Assignment Operator Unary Operators Equality and Relational Operators Conditional Operators
Chapter 3 - Statements and Control Flow
Expressions Statements If-Then Statement If-Then-Else Statement More If Statements Switch Statement While and Do-While Statements For Statement Branching Statements Exception Handling
Chapter 4 - Code Example
Example Project - A Simple Vending Machine Adding money Delivering Items Giving Change
Chapter 5 - Classes and Interfaces
Introduction Access Level Modifiers Class Declaration - Class, Methods and Fields Class Declaration - Constructors Inheritance Basics Inheritance - Constructors Inheritance - Methods and Fields Polymorphism Abstract Classes and Methods Interfaces Static Class Members Class Composition Final Classes and Class Members Generic Classes
Chapter 6 - Base Object Behaviors
Introduction Type Comparison Type Casting Object Equality - The Contract Object Equality - Common Pitfalls Object String Representation Garbage Collection Object Comparison Primitive Wrappers and Autoboxing
Chapter 7 - Data Structures
Introduction Arrays - Declaration and Creation Arrays - Basic Operations Core Collection Interfaces List and ArrayList - Basic Operations ArrayList Internals Introduction to Hash Tables Map and HashMap - Basic Operations Set and HashSet - Basic Operations
Chapter 8 - Anonymous classes and lambdas
Introduction Filtering a List Anonymous Classes Lambdas Built-in Functional Interfaces
Chapter 9 - Streams
Introduction Creating Streams Intermediate Operations Terminal Operations