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.

Java

  1. Install
  2. javac java jar javadoc

Java Basics

  1. Print String
  2. Strings
  3. Power Function
  4. Java Types and Type Conversion
  5. Function
  6. Arrays

Class, Inheritance

  1. extends
  2. Constructor
  3. Constructor Return Type
  4. Extending a Class that has Explicit Constructors
  5. static
  6. this
  7. super
  8. Access Specifiers

Abstract class, Interface

  1. abstract
  2. Interface

Package

  1. Package

Misc

  1. Collection, Map
  2. Read/Write File
  3. Convert File Encoding
  4. Complex Numbers in Java
  5. Unicode
  6. Number Literals