Inheritance

Inheritance allows one class to receive (or “inherit”) fields and methods from another class. The class that gives the features is the superclass. The class that receives them is the subclass.

Basic idea: A subclass “is a” type of its superclass.

Example: A Dog is an Animal.

A subclass inherits:

  • public methods

  • protected methods

  • public instance variables

  • protected instance variables

A subclass does NOT inherit:

  • private instance variables

  • private methods

  • constructors

Private members still exist in the object, but the subclass cannot access them directly.

Defining a subclass:

Use the keyword "extends".

Example: class Animal {

public void speak() {

System.out.println("generic sound");

}

}

class Dog extends Animal {

// Dog inherits speak()

}

If the superclass has a method, the subclass can call it directly.

Example: Dog d = new Dog(); d.speak(); // works because Dog inherits speak()

A subclass can replace a method from the superclass by writing a new version with the same name, parameters, and return type. This is method overriding.

Ex:

class Dog extends Animal {

public void speak() {

System.out.println("woof");

}

}

super refers to the superclass.

There are two uses:

  1. Call a superclass method

  2. Call a superclass constructor

Ex:

class Dog extends Animal {

public void speak() {

super.speak(); // calls Animal's speak()

System.out.println("woof");

}

}

class Animal {

private String name;

public Animal(String n) {

name = n;

}

}

class Dog extends Animal {

public Dog(String n) {

super(n); // must be first line

}

}

Constructors are not inherited.

Rules:

  • The first line of a subclass constructor must be super(...) or this(...)

  • If you do not write super(...), Java inserts super() automatically

  • If the superclass has no no‑argument constructor, the subclass must call a valid one

Polymorphism:

A superclass reference can store a subclass object.

Ex:

Animal a = new Dog();

a.speak(); // calls Dog's speak()

This is illegal:

Dog d = new Animal(); // not allowed

Because an Animal is not necessarily a Dog.

You can cast a superclass reference back to a subclass if it actually refers to that subclass.

Example:

Animal a = new Dog(); Dog d = (Dog) a; // allowed

But this causes a runtime error:

Animal a = new Animal(); Dog d = (Dog) a; // not allowed