Java: The “extends” Keyword

By Xah Lee. Date: . Last updated: .

In Java, there's the very important keyword extends.

A class declaration can use the keyword extends on another class, like this:

class C extends B { … }

When a class C extends class B, C automatically has all variables and methods defined in class B (except private variable and methods).

// example of extending a class

class B {
    int x = 0;
    void f1 () { x = x+1;}
}

class C extends B {}

public class Test1 {
    public static void main(String[] args) {
        B b = new B();
        b.f1();
        System.out.println( b.x ); // prints 1
    }
}

If class C defines a variable or method that has the same name in class B, class C's definition overrides B's.

// example of extending a class, overwriting a method
class B {
    int x;
    void setIt (int n) { x=n;}
    void increase () { x=x+1;}
}

class C extends B {
    void increase () { x=x+2;}
}

public class Test2 {
    public static void main(String[] args) {
        B b = new B();
        b.setIt(2);
        b.increase();
        System.out.println( b.x ); // prints 3

        C c = new C();
        c.setIt(2);
        c.increase();
        System.out.println( c.x ); // prints 4
    }
}

When class C extends B, we say that C is a subclass of B, and B is the superclass of C. This is called inheritence, because C inherited from B.

A class is final if it uses a final keyword in class declaration. Final classes cannot be extended.

In Java, EVERY class is a subclass of java.lang.Object.