Inheritance of static members



A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).

Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.
The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.
A subclass inherits all the members including static member (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
Inheritance of static members works in funny ways in Java. If you subclass another class, you will inherit the superclass' static members. However, the subclass does not have its own distinct copy of the static variable; the superclass, and all its subclasses share the same copy. This turns out to be a bit of a pain if you specifically want static methods which access individual static variables for each subclass in a hierarchy. You have to overload every single static method and redefine every static variable in every subclass, somewhat negating the point of inheritance.
Explanation of same copy by example:
/**
 *
 * @author Navindra K. Jha
 */
public class Super {

    static int d = 1;

    public static int getD() {
        return d;
    }
}

class Sub extends Super {

    public static int getD() {
        d++;
        return d;
    }
}

class Test {

    public static void main(String as[]) {
        System.out.println(Super.getD());
        System.out.println(Sub.getD());
        System.out.println(Super.getD());
    }
}

Output:
1
2
2

As once value of d is increases Super class getD() method also print 2 that means it is clear both using same copy of variable.


No comments:

Post a Comment