简体   繁体   中英

Static method from superclass called on subclass

I need to call a superclass static method on a subclass and be aware that it was called on a subclass. The following code shows the use case, please notice the method invocation on a subclass B.importantMethod() and the place where I need to know that it was called on subclass: //would like to get B here .

class A {
    public static void importantMethod() {
        System.out.println("???"); //would like to get B here
    }
}

class B extends A {
    //no implementation, just inheritance
}

public class Test {
    public static void main(String[] args) {
        B.importantMethod();
    }
}

Any possible way of achieving this will be good for me. My tries ended up with nothing, I always get A , not B .

This is just not possible. Static methods always belong to the class that defines them. importantMethod is a method of class A .

static methods are class methods and thus belong to that class; there is no way to do what you want. For a further explanation, see this topic . If you provide more information about the problem you are trying address this way, may be we can help you find an alternative solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM