Can we override static method in Java ?


In sort,
 Static method belongs to the class, rather than to an object of the class. As you know overriding a method means redefining behaviour of an object, but static method show the behaviour of a class as whole and it is referred by class name. So it does not redefine the behaviour of an object.

In details,
Static method should be invoked with the class name, without the need for creating an instance of the class, as below
ClassName.methodName(if args)
You can also refer to static methods with an object reference, as bellow
instanceName.methodName(if args)
A subclass inherits all the members including static member (fields, methods, and nested classes) from its superclass.



 Actually overriding a method means redefining its behaviour in subclass. But If a subclass defines a class method(static method) with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.
The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Let's look at an example that contains two classes. The first is Person, which contains one instance method and one class method and the second class, a subclass of Person, is called Friend.

/*
 * Overriding a method means redefining it.
 */
package nk;
/**
 *
 * @author Navindra Jha
 */
public class Person {

    public static void getAddress() {
        System.out.println("New Delhi, India");
    }

    public void getMobileNo() {
        System.out.println("98xxxx9989");

    }
}

class Friend extends Person {

    public static void getAddress() {
        System.out.println("Laxmi Nagar, Delhi");
    }

    @Override
    public void getMobileNo() {
        System.out.println("99xxxx9990");

    }
}

class Test {

    public static void main(String as[]) {

        Person p = new Friend();//Person object is created by redefined behavior of Friend Class
        Person.getAddress();    //getAddress() of Person is called.
        Friend.getAddress();    //getAddress() of Friend is called.
        p.getMobileNo();        //new implementation of getMobileNo() is call
    }
}

Output:
New Delhi, India
Laxmi Nagar, Delhi
99xxxx9990

“you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods—they are new methods, unique to the subclass.”

No comments:

Post a Comment