Home > DeveloperSection > Forums > Can I override a static method?
Rajesh Goswami

Total Post:29

Points:203
Posted on    April-16-2011 1:21 AM

 Java Java 
Ratings:


 1 Reply(s)
 1136  View(s)
Rate this:

Can i override a static method?

please give the example.



Amit Singh

Total Post:103

Points:721
Posted on    April-16-2011 2:52 AM

Method Overriding is done for achieving dynamic binding behavior, where the method calls are resolved at runtime. Therefore the answer is: "No", static method belongs to a class & its calls are resolved at compile time so it can not be overridden to give dynamic binding behavior. Though you can have a method with same name in derived class but it will not be dynamic behavior.
Example:
package inheritance;

public class Parent {

public static void myStaticMethod() {
System.out.println("Calling " + Parent.class);
}
}

package inheritance;

public class Child extends Parent {

public static void myStaticMethod() {
System.out.println("Calling " + Child.class);
}
}

package inheritance;

public class Test {
public static void main(String[] args) {
Parent p = new Parent();
/*
* Should call the parents implementation
*/
p.myStaticMethod();

Child c = new Child();
/*
* Should call the child implementation
*/
c.myStaticMethod();

Parent p2 = new Child();
/*
* Should call the child implementation in case of dynamic binding
* but it does not as the static method is associated with the
* reference type and here we have a reference of Parent class.
* Hence parents implementation is called.
*/
p2.myStaticMethod();
}
}
output.

Calling class inheritance.Parent
Calling class inheritance.Child
Calling class inheritance.Parent

Don't want to miss updates? Please click the below button!

Follow MindStick