Inheritance allows a new class (called a subclass)to be defined based on an existing class (called a superclass).
extendsextends is used when a class inherits from another class.
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
When a class extends a superclass, it can "override" some or all of the methods in the superclass.
@OverrideThe decorator @Override should be added before every method you override to help with type checking.
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 becauseDogoverrides themakeSoundmethod of it's superclass.
implementsimplements 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.
Used when a class implements an interface.
interface Swimmer {
void swim();
}
class Fish implements Swimmer {
public void swim() {
System.out.println("Fish swims");
}
}
Java allows multiple interfaces but only one superclass.
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.Serializable for saving and loading data.