by BehindJava

Can You Override Static Method in Java

Home » java » Can You Override Static Method in Java

This one of the most frequently asked question in Java interviews and the answer is no we cannot Override Static Method in Java. So lets start with Overriding, The name method overriding itself explains that a method is being overridden and in the object oriented programming we can achieve it by the inheritance where child object acquires all the properties upon extending the parent class.

When a child class has the same method name that is already defined in the parent class is called method overriding. Method overriding is also used to achieve runtime polymorphism also known as dynamic method dispatch. Upcasting is process in which a reference variable of parent class refers to the object of child class.

Now lets know the static method, it belongs to a class but not to the object or instance of the class. Since object creation is not required for the static method to invoke the method.

Suppose in a class if you take any method as static with some logic. Here static means it is common for all the objects in the hierarchy and now create a child class that is extending the parent class that contains the static method and here extending means a kind of updation in specific things. So that updation or changes can be done in the parent class itself because static method is common and available to all and to be more precise in Java static is just a synonm of common.

Example:

class Parent
{
    static void m1()
    {
        //define and update here 
        //since it is a static method which is common for all 
    }
}
class Child extends Parent
{
    static void m1()
    {
       //This method cannot be overriden since it is static
       //but you can access this method commonly 
    }
}