Tuesday, August 28, 2012
Can we override static method in Java - Method Hiding
Can we override static method in Java
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 class name and not by using object becaues static method can not be overridden in Java.
In last section we saw theory that we can not override static methods in Java, static method can only be hidden in sub class. Let's see an example to test that theory which says you can not override static method in Java
This output confirms that you can not override static method in Java and static method are bonded based upon type information and not based upon Object. had Static mehtod be overridden, method from Child class or ColorScreen would have been called.
That's all on discussion Can we override static method in Java or not. We have confirmed that no, 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.
Other Java tutorials from Java67 site :