静态继承

静态方法可以像普通方法一样继承,但是与普通方法不同,不可能创建“ 抽象 ”方法来强制静态方法重写。在超类中编写与静态方法具有相同签名的方法似乎是一种覆盖的形式,但实际上这只是创建一个新函数隐藏另一个。

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);
    }
}

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

public static 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 overrides the sayHello method from BaseClass
    public static void sayHello() {
        System.out.println("Static says Hi");
    }

}

运行任何这些类都会产生输出:

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

请注意,与普通继承不同,静态继承方法不会被隐藏。你始终可以使用 BaseClass.sayHello() 调用基本 sayHello 方法。但是如果在子类中找不到具有相同签名的方法,类会继承静态方法。如果两个方法的签名不同,则两个方法都可以从子类运行,即使名称相同也是如此。

静态字段以类似的方式相互隐藏。