Why doesn't Java allow static method override?

Asked 2 years ago, Updated 2 years ago, 143 views

Why can't I override the static method in Java? If possible, show me an example of how to do it.

java static overrider static-methods

2022-09-22 22:29

1 Answers

When JVM invokes a method, instance method finds and invokes the real object implementing it at runtime (multiplexed), but neither the compiler nor the JVM performs an action to locate the real object for static methods, so class method calls the type of method declared at compile time. Therefore, polymorphism does not apply in the static method.

Also, in principle, it is not possible to override, but it is possible like the code below. In Java, this is called "hiding." Hydration exists only in theory and is not a recommended technique for actual class design.

public class A{
    public static void test() {
        System.out.println("A test()");
    }
}

class B extends A{
    @Override // compilation error
    public static void test() {
        System.out.println("A test()");
    }
}
//-----------------------------------------------------------------
public class A{
    public static void test() {
        System.out.println("A test()");
    }
}

class B extends A{
    public static void test() {
        System.out.println("A test()");
    }
}


2022-09-22 22:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.