Skip to content

Inheritance (course memo)

Java. Sharing code among classes this way is called inheritance.

  • The class holding the shared code: parent class / superclass.
  • The class inheriting it: child class / subclass.
  • The superclass is a template the subclass extends; we say the subclass "inherits from" or "extends" the superclass.

Defining a parent class

java
public class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

A superclass is just a normal class — nothing special about its own declaration. Its private members are not directly usable by subclasses (they must go through public/ protected methods like getName()).

Defining a child class

java
public class Dog extends Animal {
    private int lovePoints;

    public Dog(String name, int lovePoints) {
        super(name);
        this.lovePoints = lovePoints;
    }

    public int getLovePoints() {
        return lovePoints;
    }
}
  • extends SuperclassName after the class name.
  • The subclass constructor's first line must call the superclass constructor (super(...)) with whatever arguments it needs.
  • Dog doesn't have direct access to Animal's private name field — it has to go through the inherited getName() method.
java
public class Cat extends Animal {
    private int hatePoints;

    public Cat(String name, int hatePoints) {
        super(name);
        this.hatePoints = hatePoints;
    }

    public int getHatePoints() {
        return hatePoints;
    }
}
  • Both Dog and Cat have name/getName() via Animal; only Dog has getLovePoints(), only Cat has getHatePoints().
  • Both can go into a List<Animal>, just like with interfaces.

The protected visibility

Four visibility levels total now:

  • public — everyone.
  • private — same class only.
  • default (no modifier) — same package only.
  • protected — same package, plus any subclass, regardless of that subclass's package.

protected behaves like default visibility, except subclasses outside the package can still access it — the visibility level specifically meant for sharing with subclasses.