I am familiar with static
keyword, and how it used. I understand that a static
method can be re-declared in sub-class but its definition gets hidden and remains same as of parent class. I am mentioning some links of articles I've already read:
https://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/
Why doesn't Java allow overriding of static methods?
Difference between Static and final?
When a derived class defines a static method with same signature as a static method in base class, the method in the derived class hides the method in the base class. But still the method of base class is called such as display()
method of base class.
But I am curious as to why and when there is a need to re-declare static
method of base class
in derived class if its definition cannot
overridden/altered in the derived class and the definition of base class is displayed instead?
/* Java program to show that if static method is redefined by
a derived class, then it is not overriding. */
// Superclass
class Base {
// Static method in base class which will be hidden in subclass
public static void display() {
System.out.println("Static or class method from Base");
}
// Non-static method which will be overridden in derived class
public void print() {
System.out.println("Non-static or Instance method from Base");
}
}
// Subclass
class Derived extends Base {
// This method hides display() in Base
public static void display() {
System.out.println("Static or class method from Derived");
}
// This method overrides print() in Base
public void print() {
System.out.println("Non-static or Instance method from Derived");
}
}
// Driver class
public class Test {
public static void main(String args[ ]) {
Base obj1 = new Derived();
// As per overriding rules this should call to class Derive's static
// overridden method. Since static method can not be overridden, it
// calls Base's display()
obj1.display();
// Here overriding works and Derive's print() is called
obj1.print();
}
}