Monday, July 26, 2021

Can You Overload or Override Static methods in Java? Example

Can a static method be overridden in Java, or can you override and overload static method in Java, is a common Java interview questions mostly asked to 2 years experienced Java programmers. The answer is, No, you can not override static method in Java, though you can declare a method with the same signature in a subclass. It won't be overridden in the exact sense, instead, that is called method hiding. But at the same time, you can overload static methods in Java, there is nothing wrong with declaring static methods with the same name, but different arguments. Some time interviewer also ask, Why you can not override static methods in Java? The answer to this question lies in the time of resolution.

As I said in the difference between static and dynamic binding, static methods are bonded during compile time using Type of reference variable, and not Object. If you have using IDE like Netbeans and Eclipse, and If you try to access static methods using an object, you will see warnings. As per Java coding convention, static methods should be accessed by class name rather than an object. 

In short, a static method can be overloaded, but can not be overridden in Java. If you declare,  another static method with same signature in derived class than the static method of superclass will be hidden, and any call to that static method in subclass will go to static method declared in that class itself. This is known as method hiding in Java.



Can Static Method be overridden in Java - See yourself

Can we overload and override static method in Java - WhyLet's see an example of trying to override a static method. In this Java The program, we have two classes Parent and Child, both have name() method which is static

Now, As per rules of method overriding, if a method is overridden than a call is resolved by the type of object during runtime. This means, in our test class StaticOverrideTest, p.name() in the second the example should call Child class' name() method because the reference variable of type Parent is referring an object of Child, but instead, it call name() method of Parent class itself. 

This happens, because static methods are resolved or bonded during compile time, and only information that is available, and used by the compiler is a type of reference variable. Since p was a reference variable of the Parent type, the name() method from the Parent class was called. Now, In order to prove that static method can be hidden, if we call Child.name() or c.name(), it will call name() method from Child class. 

This means static methods can not be overridden in Java, they can only be hidden. This also answers, Why the static method can not be overridden in Java, because they are resolved during compile time. By the way, this example doesn't show, whether you can overload static method or not, but you can. See this tutorial, for an example of an overloading static method in Java. 

/**
 * Java Program to show that, you can not override static method in Java.
 * If you declare same method in subclass then, It's known as method hiding.
 *
 * @author Javin Paul
 */
public class StaticOverrideTest {
   
   
    public static void main(String args[]) {
       
        Parent p = new Parent();
        p.name();   // should call static method from super class (Parent)
                    // because type of reference variable
                    // p is Parent
       
        p = new Child();
        p.name();  // as per overriding rules this should call to child's static 
                   // overridden method. Since static method can not be overridden
                   // , it will call parent static method
                   // because Type of p is Parent.
       
        Child c = new Child();
        c.name();  // will call child static method because static method 
                   // get called by type of Class
       
    }
}

class Parent{
   
    /*
     * original static method in super class which will be hidden
     * in subclass.
     */
    public static void name(){
        System.out.println("static method from Parent");
    }
}

class Child extends Parent{
   
    /*
     * Static method with same signature as in super class,
     * Since static method can not be overridden, this is called
     * method hiding. Now, if you call Child.name(), this method
     * will be called, also any call to name() in this particular
     * class will go to this method, because super class method is hidden.
     */
    public static void name(){
        System.out.println("static method from Child");
    }
}

Output
static method from Parent
static method from Parent
static method from Child

That's all on this Java interview question guys. Remember, Static methods can not be overridden in Java, but they can be overloaded and hidden in Java. We have also touched based on What is method hiding in Java, and learned Why Static method can not be overridden in Java, since they are bonded during compile time by using a type of Class, and not at runtime using Objects.

Related Java Interview Questions from Javarevisited Blog

11 comments:

  1. I faced this question 2 times during my interview. Happy to see it here. I know the answer but I am glad to see it with example. :)

    ReplyDelete
  2. Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). A static method is not associated with any instance of a class so the concept is not applicable.

    There were two considerations driving Java's design that impacted this. One was a concern with performance: there had been a lot of criticism of Smalltalk about it being too slow (garbage collection and polymorphic calls being part of that) and Java's creators were determined to avoid that. Another was the decision that the target audience for Java was C++ developers. Making static methods work the way they do had the benefit of familiarity for C++ programmers and was also very fast, because there's no going up the class hierarchy to figure out which method to call, you go straight to the class and call the specified method.

    ReplyDelete
  3. Java doesn't allow overriding of static methods..
    class stat13
    {
    static void show()
    {
    System.out.println("Static in base");
    }
    public static void main(String[] ar)
    {
    new next().show();
    }
    }


    class next extends stat13
    {
    static void show()
    {
    System.out.println("Static in derived");
    }
    }
    As shown above This is "hiding", not "overriding". To see this, change the main method to the following..
    public static void main (String[] arghh) {
    next n = new next();
    n.show();
    stat13 s = n;
    s.show();
    }
    This should print:

    Static in derived
    Static in base
    If there was real overriding going on, then you would see:

    Static in derived
    Static in derived
    It is generally thought to be bad style to invoke a static method using an instance type ... like you are doing ... because it is easy to think you are invoking an instance method, and get confused into thinking that overriding is happening. A Java style checker / code audit tool will typically flag this as a style error / potential bug.

    ReplyDelete
  4. In Java 1.5 or greater, you can use @Override annotation to see whether you are 'really' overriding the method. It's a free check by the compiler.

    ReplyDelete
  5. @born2perform, Indeed, that's a useful check and one of the java coding best practice, I have shared few tips on @Override annotation in Java, you may like. By the way, with static methods, you can not use @Override annotation, it's compilation error.

    ReplyDelete
  6. @Anonymous, Thanks for kind words, and I am glad that you find this Java Blog useful.

    Javin

    ReplyDelete
  7. Method Overriding VS Method Hiding in java



    If and instance method in a subclass has same signature and return type as instance method in the superclass ,it is called overriding.Method signature means name, and the number and the type of its parameters. Number ,type of the parameters should be same in method written in super class and sub class.

    overriding method can also return a subtype of the type returned by the super class method. This is called a co-variant return type.
    Foe example

    public class Animal {

    public void test() {

    }
    }



    public class Dog extends Animal {

    public void test() {
    }

    }test() method in Dog class is overridden .

    If a class method in subclass has the same signature as a class method in the superclass, This is called method hiding.


    See further details at this location :

    http://efectivejava.blogspot.in/2013/09/method-overriding-vs-method-hiding-in.html

    ReplyDelete
  8. I tried to override static variable in Java 7. I am able to do it.

    public class TestStatic {

    protected static String name = "MockingJay";

    }

    public class TestParent extends TestStatic{

    protected static String name = "test";

    public static void main(String[] args) {


    System.out.println("name: " + name);

    }

    }

    output is:
    test

    ReplyDelete
  9. @AlienOnEarth, it's not overriding but hiding, static variables are resolved at compile time by using Type of variable, Sine you are accessing them in TestParent class, it's print "test"

    ReplyDelete
  10. Hello ,

    I would like to know whether it is "CORRECT" to call static method using objects of the class.

    Though it is certainly possible, does it not defeat the whole purpose of static modifier.

    "Static" is always associated with a class rather than its object.

    Please correct me if I am wrong, however I felt compelled to post my query.

    Regards,
    Ravi Prakash



    ReplyDelete