Friday, 31 January 2014

Is it possible to Override Static Method?

Obviously............ NO.

We cannot override static methods. We cannot change the behavior of static methods within an inheriting class.

When you are trying to override the final method you would get an compile time error, But when you try to override a static method you dont get any compile type errors but the behavior cannot be overridden.Yes you can write overridding code but the behavior cannot be overridden. Java dont stop you to do that.

Why static methods cannot be overridden is.. because they are class methods hence calling the static methods defined by compiler at compile time. they are not belongs to Object state.

Have a look at below example


public class ParentClass {
public static void staticMethod()
{
System.out.println("ParentClass Static Method");
}
}

public class ChildClass extends ParentClass {
public static void staticMethod()
{
System.out.println("ChildClass Static Method");
}
public static void main(String[] args) {
ParentClass parentClassWithChildObject = new ChildClass();
ParentClass.staticMethod();
parentClassWithChildObject.staticMethod(); //calls superclass staticMethod even thought it holds childClass object at runtime
ChildClass.staticMethod();
}
}

The output comes like
ParentClass Static Method
ParentClass Static Method
ChildClass Static Method

Note: We can overload static methods.

No comments:

Post a Comment

Followers