Java Tutorial: The “extend” Keyword

, , …,

In Java, there's the very important “extend” keyword.

A class declaration can use the extend keyword 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. (think of it as automatic copy/paste system.)

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

class B {
    int x;
    void setIt (int n) { x=n;}
    void increase () { x=x+1;}
    void triple () {x=x*3;};
    int returnIt () {return x;}
}

class C extends B {
    void triple () {x=x+3;} // override existing method
    void quadruple () {x=x*4;} // new method
}

public class GetRich {
    public static void main(String[] args) {
        B b = new B();
        b.setIt(2);
        b.increase();
        b.triple();
        System.out.println( b.returnIt() ); // prints 9

        C c = new C();
        c.setIt(2);
        c.increase();
        c.triple();
        System.out.println( c.returnIt() ); // prints 6
    }
}

In the above code, class C inherits all class B's variables and methods. Class C overrides the “triple” method, and added a “quadruple” method.

Now, other classes can extend your Class C, and inherit all members and methods of class C (which includes those in B). In this way, a tree hierarchy (tree) is formed.

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.

Two or more classes can inherit from the same parent class (i.e. a class can have many children). However, a class can NOT inherit from multiple classes. (i.e. each class can only have one parent.)

In Java, EVERY class is a subclass of java.lang.Object (or subclass of its subclasses). Every class in Java is a node on this giant tree.

blog comments powered by Disqus