Inheritance (Java)

Inheritance lets one class (the subclass) reuse and extend the fields and methods of another class (the superclass). You set it up with the extends keyword.

Java

The subclass automatically gets the public and protected members of its parent, and can add new ones or override existing ones. Use super to call the parent's constructor or methods.

Inheritance models an 'is-a' relationship: a Cat is an Animal. Every class in Java ultimately inherits from the built-in Object class.

Examples

Java

class Animal {
    String speak() { return "..."; }
}

class Cat extends Animal {
    String speak() { return "meow"; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Cat().speak());
    }
}

Output:

meow

Learn it in a lesson

See also

Back to the Dictionary