104

I'd like to know:

  1. Why can't static methods be overridden in Java?
  2. Can static methods be overloaded in Java?
Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
giri
  • 26,773
  • 63
  • 143
  • 176

19 Answers19

128

Static methods can not be overridden in the exact sense of the word, but they can hide parent static methods

In practice it means that the compiler will decide which method to execute at the compile time, and not at the runtime, as it does with overridden instance methods.

For a neat example have a look here.

And this is java documentation explaining the difference between overriding instance methods and hiding class (static) methods.

Overriding: Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods)

Hiding: Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.

ashishakp
  • 111
  • 1
  • 8
opensas
  • 60,462
  • 79
  • 252
  • 386
  • 3
    Thanks, your link helped me to find out my answer. I read this in your given link: "Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods)." This was the answer for which I was searching. Thanks. – Mital Pritmani Dec 05 '11 at 12:22
  • 2
    I found more in depth explanation on [CodeRanch](http://www.coderanch.com/how-to/java/OverridingVsHiding) – realPK Feb 23 '14 at 17:44
  • 2
    For this answer to really be completed, you should probably answer the second part of the question. – Tim M. Jul 20 '17 at 15:49
39

Static methods can not be overridden because there is nothing to override, as they would be two different methods. For example

static class Class1 {
    public static int Method1(){
          return 0;
    }
}
static class Class2 extends Class1 {
    public static int Method1(){
          return 1;
    }

}
public static class Main {
    public static void main(String[] args){
          //Must explicitly chose Method1 from Class1 or Class2
          Class1.Method1();
          Class2.Method1();
    }
}

And yes static methods can be overloaded just like any other method.

VolatileDream
  • 1,083
  • 7
  • 15
  • 4
    Can you put more light on **Static methods can not be overridden because there is nothing to override**? What do someone get when doing this: Class1 c1 = new Class2(); Class2 c2 = new Class2(); Do I expect Method1() from Class2 called in both cases or NOT? – realPK Feb 23 '14 at 17:34
  • 2
    There is nothing to override for a static method, because static methods are linked at compile time, unlike normal methods, whose execution is determined at runtime. You can NOT expect `c1.Method1()` and `c2.Method1()` to call the same function, in fact, the compiler warns you that invoking static functions in this way is not a smart thing to do. – VolatileDream Feb 23 '14 at 21:20
  • Correct me if I am still confused - 1. ClassName.methodName() is the best practice to invoke static methods in Java 2. Reference type matters when dealing with static methods and NOT the instantiated type 3. We can hide static methods in subclass but CAN'T override even though the code looks like its overriding the method. – realPK Feb 23 '14 at 22:01
  • Correct on all counts. I've put up a small demo sample [here](https://gist.github.com/VolatileDream/9201901). – VolatileDream Feb 25 '14 at 03:12
  • 1
    In java, we can’t make Top level class static. Only nested classes can be static.The solution which above user provided is completely wrong. – Prasad May 08 '17 at 12:43
  • I guess my problem is that I don't understand the definition of Overriding a method because in practice is exactly the same, you have 2 methods, and when calling the "overwritten" the call will go as planned (https://onecompiler.com/java/3x4qw4gpb). I do not understand why should we care or why is it important if the compiler does one or another thing in order for us to call it Override. One can argue the implementation is just hiding the method but that is basically what normal overriding does isn't it? – White_King Jul 07 '21 at 08:17
  • https://stackoverflow.com/a/5436790/1180993 explains that inheritance won't work due to this kind of implementation, therefore, is not actually an Override. – White_King Jul 07 '21 at 08:29
22

Static methods cannot be overridden because they are not dispatched on the object instance at runtime. The compiler decides which method gets called.

This is why you get a compiler warning when you write

 MyClass myObject = new MyClass();
 myObject.myStaticMethod();
 // should be written as
 MyClass.myStaticMethod()
 // because it is not dispatched on myObject
 myObject = new MySubClass();
 myObject.myStaticMethod(); 
 // still calls the static method in MyClass, NOT in MySubClass

Static methods can be overloaded (meaning that you can have the same method name for several methods as long as they have different parameter types).

 Integer.parseInt("10");
 Integer.parseInt("AA", 16);
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 1
    In Delphi static methods can be overridden - they just have pointer to VMT instead of object instance (and example above would do call `MySubClass.myStaticMethod`). – Ha. Mar 19 '10 at 07:09
  • I don't think a warning is a valid proof for your answer. Pragmatically it CAN be overridden and have the same functionality as a common method but the central point will be, I guess, in the definition of "overridden" you have (and are not providing). – White_King Jul 07 '21 at 08:08
  • Method overriding in Java (and its connection to dynamic dispatch) is a very precise term. And it cannot be done for static methods. @White_King – Thilo Jul 07 '21 at 12:59
9

Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.

Community
  • 1
  • 1
Kumar Manish
  • 1,166
  • 1
  • 16
  • 28
5

Static methods can not be overridden because they are not part of the object's state. Rather, they belongs to the class (i.e they are class methods). It is ok to overload static (and final) methods.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
Manoranjan
  • 51
  • 1
  • 1
4

Overloading is also called static binding, so as soon as the word static is used it means a static method cannot show run-time polymorphism.

We cannot override a static method but presence of different implementations of the same static method in a super class and its sub class is valid. Its just that the derived class will hide the implementations of the base class.

For static methods, the method call depends on the type of reference and not which object is being referred, i.e. Static method belongs only to a class and not its instances , so the method call is decided at the compile time itself.

Whereas in case of method overloading static methods can be overloaded iff they have diff number or types of parameters. If two methods have the same name and the same parameter list then they cannot be defined different only by using the 'static' keyword.

  • A method signature is the method name and the number, type and **order of its parameters**. Which means even if the order of the parameters in method is changed , it can be successfully overloaded. – iCantC Mar 12 '19 at 08:49
3

No,Static methods can't be overriden as it is part of a class rather than an object. But one can overload static method.

praveen
  • 63
  • 5
3

Static methods are a method whose single copy is shared by all the objects of the class. A static method belongs to the class rather than objects. since static methods are not dependent on the objects, Java Compiler need not wait till the creation of the objects so to call a static method we use syntax like ClassName.method() ;

In the case of method overloading, methods should be in the same class to overload.even if they are declared as static it is possible to overload them as,

   Class Sample
    {
         static int calculate(int a,int b,int c)
           {
                int res = a+b+c;
                return res;
           }
           static int calculate(int a,int b)
           {
                int res = a*b;
                return res;
           }
}
class Test
{
   public static void main(String []args)
   {
     int res = Sample.calculate(10,20,30);
   }
}

But in the case of method overriding, the method in the super class and the method in the sub class act as a different method. the super class will have its own copy and the sub class will have its own copy so it does not come under method overriding.

Pravin Kamble
  • 81
  • 1
  • 9
3

If I m calling the method by using SubClass name MysubClass then subclass method display what it means static method can be overridden or not

class MyClass {
    static void myStaticMethod() {
        System.out.println("Im in sta1");
    }
}

class MySubClass extends MyClass {

    static void  myStaticMethod() {
        System.out.println("Im in sta123");
    }
}

public class My {
    public static void main(String arg[]) {

        MyClass myObject = new MyClass();
        myObject.myStaticMethod();
        // should be written as
        MyClass.myStaticMethod();
        // calling from subclass name
        MySubClass.myStaticMethod();
        myObject = new MySubClass();
        myObject.myStaticMethod(); 
        // still calls the static method in MyClass, NOT in MySubClass
    }
}
mtk
  • 13,221
  • 16
  • 72
  • 112
2

static methods are class level methods.

Hiding concept is used for static methods.

See : http://www.coderanch.com/how-to/java/OverridingVsHiding

roottraveller
  • 7,942
  • 7
  • 60
  • 65
NarutoUzumaki
  • 91
  • 1
  • 1
  • 11
2
class SuperType {

    public static void  classMethod(){
        System.out.println("Super type class method");
    }
    public void instancemethod(){
        System.out.println("Super Type instance method");
    }
}


public class SubType extends SuperType{


    public static void classMethod(){
        System.out.println("Sub type class method");
    }
    public void instancemethod(){
        System.out.println("Sub Type instance method");
    }
    public static void main(String args[]){
        SubType s=new SubType();
        SuperType su=s;
        SuperType.classMethod();// Prints.....Super type class method
        su.classMethod();   //Prints.....Super type class method
        SubType.classMethod(); //Prints.....Sub type class method 
    }
}

This example for static method overriding

Note: if we call a static method with object reference, then reference type(class) static method will be called, not object class static method.

Static method belongs to class only.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • Static methods are **not** *overridden*, they are *hidden*. Read more about it at http://docs.oracle.com/javase/tutorial/java/IandI/override.html – Pshemo Jun 01 '14 at 11:13
0

The very purpose of using the static method is to access the method of a class without creating an instance for it.It will make no sense if we override that method since they will be accessed by classname.method()

Sathesh
  • 6,323
  • 6
  • 36
  • 48
0

No, you cannot override a static method. The static resolves against the class, not the instance.

public class Parent { 
    public static String getCName() { 
        return "I am the parent"; 
    } 
} 

public class Child extends Parent { 
    public static String getCName() { 
        return "I am the child"; 
    } 
} 

Each class has a static method getCName(). When you call on the Class name it behaves as you would expect and each returns the expected value.

@Test 
public void testGetCNameOnClass() { 
    assertThat(Parent.getCName(), is("I am the parent")); 
    assertThat(Child.getCName(), is("I am the child")); 
} 

No surprises in this unit test. But this is not overriding.This declaring something that has a name collision.

If we try to reach the static from an instance of the class (not a good practice), then it really shows:

private Parent cp = new Child(); 
`enter code here`
assertThat(cp.getCName(), is("I am the parent")); 

Even though cp is a Child, the static is resolved through the declared type, Parent, instead of the actual type of the object. For non-statics, this is resolved correctly because a non-static method can override a method of its parent.

orique
  • 1,295
  • 1
  • 27
  • 36
0

You can overload a static method but you can't override a static method. Actually you can rewrite a static method in subclasses but this is not called a override because override should be related to polymorphism and dynamic binding. The static method belongs to the class so has nothing to do with those concepts. The rewrite of static method is more like a shadowing.

charles_ma
  • 786
  • 7
  • 10
0

I design a code of static method overriding.I think It is override easily.Please clear me how its unable to override static members.Here is my code-

class Class1 {
    public static int Method1(){
          System.out.println("true");
          return 0;
    }
}
class Class2 extends Class1 {
    public static int Method1(){
   System.out.println("false");
          return 1;
    }

}
public class Mai {
    public static void main(String[] args){
           Class2 c=new Class2();
          //Must explicitly chose Method1 from Class1 or Class2
          //Class1.Method1();
          c.Method1();
    }
}
Baby Groot
  • 4,637
  • 39
  • 52
  • 71
Nitin
  • 1
0

It’s actually pretty simple to understand – Everything that is marked static belongs to the class only, for example static method cannot be inherited in the sub class because they belong to the class in which they have been declared. Refer static keyword.

The best answer i found of this question is:

http://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/

hitesh141
  • 963
  • 12
  • 25
0

As any static method is part of class not instance so it is not possible to override static method

Pavan T
  • 716
  • 9
  • 12
0

From Why doesn't Java allow overriding of static methods?

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 have the benefit of familiarity for C++ programmers and were also very fast because there's no need to wait until runtime to figure out which method to call.

Community
  • 1
  • 1
Tejas Bagade
  • 163
  • 1
  • 4
-1

Definitely, we cannot override static methods in Java. Because JVM resolves correct overridden method based upon the object at run-time by using dynamic binding in Java.

However, the static method in Java is associated with Class rather than the object and resolved and bonded during compile time.

Jimesh Shah
  • 113
  • 10