Why can't static methods be abstract in Java?

后端 未结 25 2658
不思量自难忘°
不思量自难忘° 2020-11-22 08:34

The question is in Java why can\'t I define an abstract static method? for example

abstract class foo {
    abstract void bar( ); // <-- this is ok
    ab         


        
25条回答
  •  温柔的废话
    2020-11-22 08:51

    I see that there are a god-zillion answers already but I don't see any practical solutions. Of course this is a real problem and there is no good reason for excluding this syntax in Java. Since the original question lacks a context where this may be need, I provide both a context and a solution:

    Suppose you have a static method in a bunch of classes that are identical. These methods call a static method that is class specific:

    class C1 {
        static void doWork() {
            ...
            for (int k: list)
                doMoreWork(k);
            ...
        }
        private static void doMoreWork(int k) {
            // code specific to class C1
        }
    }
    class C2 {
        static void doWork() {
            ...
            for (int k: list)
                doMoreWork(k);
            ...
        }
        private static void doMoreWork(int k) {
            // code specific to class C2
        }
    }
    

    doWork() methods in C1 and C2 are identical. There may be a lot of these calsses: C3 C4 etc. If static abstract was allowed, you'd eliminate the duplicate code by doing something like:

    abstract class C {
        static void doWork() {
            ...
            for (int k: list)
                doMoreWork(k);
            ...
        }
    
        static abstract void doMoreWork(int k);
    }
    
    class C1 extends C {
        private static void doMoreWork(int k) {
            // code for class C1
        }
    }
    
    class C2 extends C {
        private static void doMoreWork(int k) {
            // code for class C2
        }
    }
    

    but this would not compile because static abstract combination is not allowed. However, this can be circumvented with static class construct, which is allowed:

    abstract class C {
        void doWork() {
            ...
            for (int k: list)
                doMoreWork(k);
            ...
        }
        abstract void doMoreWork(int k);
    }
    class C1 {
        private static final C c = new  C(){  
            @Override void doMoreWork(int k) {
                System.out.println("code for C1");
            }
        };
        public static void doWork() {
            c.doWork();
        }
    }
    class C2 {
        private static final C c = new C() {
            @Override void doMoreWork(int k) {
                System.out.println("code for C2");
            }
        };
        public static void doWork() {
            c.doWork();
        }
    }
    

    With this solution the only code that is duplicated is

        public static void doWork() {
            c.doWork();
        }
    

提交回复
热议问题