Welcome to my blog, hope you enjoy reading
RSS

Wednesday 24 April 2013

Can we override static method in Java - Method Hiding

Can we override static method in Java - Method Hiding

No, you cannot override static method in Java because method overriding is based upon dynamic binding at runtime and static methods are bonded using static binding at compile time. Though you can declare a method with same name and method signature in sub class which does look like you can override static method in Java but in reality that is method hiding. Java won't resolve method call at runtime and depending upon type of Object which is used to call static method, corresponding method will be called. It means if you use Parent class's type to call static method, original static will be called from patent class, on ther other hand if you use Child class's type to call static method, method from child class will be called. In short you can not override static method in Java. If you use Java IDE like Eclipse or Netbeans, they will show warning that static method should be called using classname and not by using object becaues static method can not be overridden in Java.

package com.javanotes2all.java.inheritence;

public class CanWeOverrideStaticMethod
{
public static void main(String args[])
{
Screen scrn = new ColorScreen();
//if we can override static ,
//this should call method from Child class
//IDE will show warning, static method should be called from classname
scrn.staticMethod();
scrn.nonStaticMethod();
}
}

class Screen
{
/*
* public static method which can not be overridden in Java
*/
public static void staticMethod()
{
System.out.println("Static method from parent class");
}
/**
* non static method
*/
public void nonStaticMethod()
{
System.out.println("non-Static method from parent class");
}
}

class ColorScreen extends Screen{
/*
* static method of same name and method signature as existed in super
* class, this is not method overriding instead this is called
* method hiding in Java
*/
public static void staticMethod()
{
System.err.println("Overridden static method in Child Class in Java");
}
/**
* non static method
*/
public void nonStaticMethod()
{
System.out.println("non-Static method from Child class");
}
}

output:
Static method from parent class
non-Static method from Child class

we can not override static method, we can only hide static method in Java. Creating static method with same name and mehtod signature is called Method hiding in Java.


0 comments: