Java abstract static Workaround

前端 未结 15 2024
猫巷女王i
猫巷女王i 2020-12-29 04:43

I understand that neither a abstract class nor an interface can contain a method that is both abstract and static because of ambiguity problems, but is there a workaround?

15条回答
  •  渐次进展
    2020-12-29 05:17

    static methods can't be abstract because they aren't virtual. Therefore anywhere that calls them has to have the concrete type with the implementation. If you want to enforce that all implementations of an interface have a certain static method, then that suggests a unit test is required.

    abstract class A
    {
        public static void foo()
        {
            java.lang.System.out.println("A::foo");
        }
    
        public void bar()
        {
    
            java.lang.System.out.println("A::bar");
        }
    }
    
    class B extends A
    {
        public static void foo()
        {
            java.lang.System.out.println("B::foo");
        }
    
        public void bar()
        {
    
            java.lang.System.out.println("B::bar");
        }
    }
    
    public class Main
    {
        public static void main(String[] args)
        {
            B b = new B();
            b.foo();
            b.bar();
    
            A a = b;
            a.foo();
            a.bar();
        }
    }
    

提交回复
热议问题