Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

extends

Declares inheritance: the class gets the parent's fields and methods.

Available since: Java 1.0

Syntax

class Child extends Parent { … }

Examples

A subclass overrides a parent method:

class Animal {
    String sound() {
        return "...";
    }
}
 
class Cat extends Animal {
    @Override
    String sound() {
        return "Meow";
    }
}
 
void main() {
    Animal a = new Cat();
    IO.println(a.sound());
}

Output:

Meow

Notes

A class extends only one class; every class implicitly extends Object. An interface can extend other interfaces with extends, several at once. In generics extends sets a type bound: <T extends Comparable<T>>.

The @Override annotation is optional, but with it the compiler checks that the method really overrides a parent one.

See also

  • super — Refers to the parent class: calls its constructor or its version of a method.
  • implements — Lists the interfaces that a class implements.
  • abstract — Marks a class that cannot be instantiated and a method without a body that subclasses implement.
  • final — Forbids reassigning a variable, overriding a method or extending a class.

In the tutorial

  • Inheritance — Class inheritance in Java: extends, protected, calling super(...), overriding methods and the @Override annotation.

Thanks for reading!

Donate to the site — we work hard for you.