Lesson Overview

Welcome to our exciting Java journey! Today's lesson focuses on Interfaces, Abstract Classes, and Simple Inheritance, which are essential to object-oriented programming. We'll unravel these concepts, understand their roles, and learn how to use them effectively. Our voyage will take us from interfaces to abstract classes, concluding with inheritance. Are you ready to boost your Java skills? Let's dive in!

Diving into Interfaces

Think of an Interface as a contract or a set of guidelines. A class can follow these guidelines or implement the interface. In this case, we have an interface, FootballPlayer, which represents the behaviors of a football player such as dribble(), pass(), and shoot().

interface FootballPlayer {
    void dribble();
    void pass();
    void shoot();
}
Implementing Interfaces

To follow an Interface, a class needs to implement it. This action necessitates the definition of all its methods. So, we create a Forward class that promises to adhere to our FootballPlayer interface:

class Forward implements FootballPlayer {
    // Dribbling like a forward player
    public void dribble() {
        System.out.println("Dribbling forward...");
    }

    // Passing pattern of a forward player
    public void pass() {
        System.out.println("Passing to a teammate...");
    }

    // How a forward player takes a shot
    public void shoot() {
        System.out.println("Shooting towards the goal...");
    }
}

Here, the Forward class is following the rules set by the FootballPlayer interface. If the Forward class does not implement one of the required methods, Java will throw an error.

Exploring Abstract Classes

Abstract classes serve as blueprints for other classes. They can't be instantiated but can provide a skeleton upon which to build. Let's demonstrate this with an Animal abstract class:

abstract class Animal {
    // How the animal eats: this method has not been implemented yet
    abstract void eat();

    void breathe() { // All animals breathe
        System.out.println("Breathing...");
    }
}

In the Animal class, we declare eat() as an abstract method, meaning subclasses must provide their own implementation. breathe() is a standard method, which all subclasses will inherit.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal