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 X3 {
    public static void main(String[] args) {
        B b = new B();
        System.out.println( b.returnIt() ); // prints 9

        C c = new C();
        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 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.

In Java, EVERY class is a subclass of java.lang.Object. java.lang Class Hierarchy (Java Platform SE 8 )

blog comments powered by Disqus