Eroxl's Notes
Inheritance

Inheritance allows a new class (called a subclass)to be defined based on an existing class (called a superclass).

Implementation

extends

extends is used when a class inherits from another class.

Example

class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks");
        super.makeSound();
    }
}

Dog dog = new Dog();
dog.bark() // Dog barks
           // Animal makes a sound

dog.makeSound() // Animal makes a sound

Overriding

When a class extends a superclass, it can "override" some or all of the methods in the superclass.

@Override

The decorator @Override should be added before every method you override to help with type checking.

Example

class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
	@Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

Dog dog = new Dog();
dog.makeSound() // Dog barks

Notice how System.out.println("Animal makes a sound"); is never run because Dog overrides the makeSound method of it's superclass.

implements

implements is used when a class implements a interface. When a class implements an interface it must provide implementations for all methods defined in the interface.

Example

Used when a class implements an interface.

interface Swimmer {
    void swim();
}

class Fish implements Swimmer {
    public void swim() {
        System.out.println("Fish swims");
    }
}

Multiple Interfaces

Java allows multiple interfaces but only one superclass.

Example

import java.io.Serializable;

interface MusicTrack {
    void play();
}

class MP3Track implements Serializable, MusicTrack {
    public void play() {
        System.out.println("Playing music...");
    }
}
  • MP3Track can be used as a MusicTrack for playing songs.
  • It can also be used as Serializable for saving and loading data.