CAN I OVERRIDE A STATIC METHOD?

Rajesh Goswami

Total Post:29

Points:203
Posted by  Rajesh Goswami
Java 
 1458  View(s)
Ratings:
Rate this:

Can i override a static method?

please give the example.

  1. Amit Singh

    Post:103

    Points:721
    Re: Can I override a static method?

    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!