Buscar este blog

miércoles, 21 de abril de 2010

La palabra reservada "extends" en Java

In java, there's the very important “extends” 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 a internal copying mechanism)

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

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.

Other classes can extend Class C, as to 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 A, and A 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. However, a class can only have one parent. In other words, in Java, you cannot subclass from multiple classes.

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

No hay comentarios:

Publicar un comentario