I would like to know the reason why this is first allowed in Java (or oops in general) I remember that the static methods are common for both parent and child class
public class Redefine extends Parent{
public static void test () {
}
}
class Parent{
public static void test () {
}
}
Q1 : Since Overriding is not supported for static methods , how can both classe contain same methods ?
Q2 : If change the method in static to throw an exception not defined its not compiling. why is the case. Its obviously not overriding so i should be allowed to throw new exceptions right ?
public class Redefine extends Parent{
public static void test () throws Exception{
}
}
No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time. So, we cannot override static methods.
We all know that we can't redefine Static Method. We'll try to explore the reasoning and alternatives to achieve the similar behavior. Redefinition is to over-ride the default implementation of the method in the subclass. This provides us the degree of polymorphism.
To call a static method from a child class, use the parent keyword inside the child class. Here, the static method can be public or protected .
Static methods cannot be Redefined In OO ABAP the polymorphism would be achieved using Method Redefinition.
A1:: static
method are per-class. They have nothing to do with inheritance hierarchies in terms of polymorphism. So calling Parent.test()
will call the parent method, while calling Redefine.test()
will call the child.
A2: JLS 8.4.8 writes:
If a class declares a static method m, then the declaration m is said to hide any method m', where the signature of m is a subsignature (§8.4.2) of the signature of m', in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class.
A method declaration must not have a throws clause that conflicts (§8.4.6) with that of any method that it overrides or hides; otherwise, a compile-time error occurs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With