calling a super method from a static method

后端 未结 6 1447
天涯浪人
天涯浪人 2020-12-05 18:14

Is it possible to call a super static method from child static method?

I mean, in a generic way, so far now I have the following:

public class BaseCo         


        
6条回答
  •  长情又很酷
    2020-12-05 18:51

    The whole inheritance concept isn't applied to static elements in Java. E.g., static method can't override another static method.
    So, no, you'll have to call it by name or make them instance methods of some object. (You might want to check out one of factory patterns in particular).

    A practical example

    class A {
        static void test() {
            System.out.println("A");
        }
    }
    class B extends A {
        static void test() {
            System.out.println("B");
        }
    }
    
        A a = new B();
        B b = new B();
        a.test();
        b.test();
    

    This prints A and then B. I.e., invoked method depends on how variable is declared and nothing else.

提交回复
热议问题