Static Inheritance

suggest change

A static method can be inherited similar to normal methods, however unlike normal methods it is impossible to create “abstract” methods in order to force static method overriding. Writing a method with the same signature as a static method in a super class appears to be a form of overriding, but really this simply creates a new function that hides the other.

// BaseClass.java
public class BaseClass {
    
    public static int num = 5;

    public static void sayHello() {
        System.out.println("Hello");
    }

    public static void main(String[] args) {
        BaseClass.sayHello();
        System.out.println("BaseClass's num: " + BaseClass.num);
            
        SubClass.sayHello();
        //This will be different than the above statement's output, since it runs
        //A different method
        SubClass.sayHello(true);
        
        StaticOverride.sayHello();
        System.out.println("StaticOverride's num: " + StaticOverride.num);
    }
}

// SubClass.java
public class SubClass extends BaseClass {
    
    //Inherits the sayHello function, but does not override it   
    public static void sayHello(boolean test) {
        System.out.println("Hey");
    }
}

// StaticOverride.java
public class StaticOverride extends BaseClass {

    //Hides the num field from BaseClass
    //You can even change the type, since this doesn't affect the signature
    public static String num = "test";
        
    //Cannot use @Override annotation, since this is static
    //This hides the sayHello method from BaseClass
    public static void sayHello() {
        System.out.println("Static says Hi");
    }

}

Running BaseClass produces the output:

Hello
BaseClass's num: 5
Hello
Hey
Static says Hi
StaticOverride's num: test

Note that unlike instance overriding, a hidden static method remains accessible: you can always call the base sayHello method by using BaseClass.sayHello(). But classes do inherit static methods if no methods with the same signature are found in the subclass. If two methods' signatures vary, both methods can be run from the subclass, even if the name is the same.

Static fields hide each other in a similar way.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents