Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override and overload static methods in Java?

I'd like to know:

  1. Why can't static methods be overridden in Java?
  2. Can static methods be overloaded in Java?
like image 616
giri Avatar asked Mar 19 '10 05:03

giri


People also ask

Can we override and overload static methods?

Overloading is the mechanism of binding the method call with the method body dynamically based on the parameters passed to the method call. Static methods are bonded at compile time using static binding. Therefore, we cannot override static methods in Java.

Can we overload and override same method in Java?

Yes it is possible, you can overload and override a function in the same class but you would not be able to overload a function in two different classes as it is logically not possible.


2 Answers

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.

like image 195
opensas Avatar answered Oct 19 '22 16:10

opensas


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.

like image 38
VolatileDream Avatar answered Oct 19 '22 16:10

VolatileDream