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
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()");
}
}
© 2024 OneMinuteCode. All rights reserved.