CRITICAL
Rule Definition
Hiding is all about polymorphism. This means that the OO designer expects to override methods and use polymorphism so that code calling methods through a base class will end up executing different methods depending on the instance being used. This is not the case with static methods. When static methods are called, there is no polymorphism in play. It is always the static method of the type used to reference the object used that is called. Hiding static methods is a misuse of OO practices that results in misunderstanding of what is going to be executed at runtime and thus leads to unexpected behavior, jeopardizing the stability of the application.
Remediation
Review the design of the Method
Violation Code Sample
class Foo { public static void classMethod() { System.out.println("classMethod() in Foo"); } public void instanceMethod() { System.out.println("instanceMethod() in Foo"); } } class Bar extends Foo { public static void classMethod() { System.out.println("classMethod() in Bar"); } public void instanceMethod() { System.out.println("instanceMethod() in Bar"); } } class Test { public static void main(String[] args) { Foo f = new Bar(); f.instanceMethod(); f.classMethod(); } } // If you run this, the output is // instanceMethod() in Bar // classMethod() in Foo
Fixed Code Sample
class Foo { public static void classMethod() { System.out.println("classMethod() in Foo"); } public void instanceMethod() { System.out.println("instanceMethod() in Foo"); } } class Bar extends Foo { //Simply not override the static (class) methods: classMethod. public void instanceMethod() { System.out.println("instanceMethod() in Bar"); } } class Test { public static void main(String[] args) { Foo f = new Bar(); f.instanceMethod(); //Rather than writing: //f.classMethod(); //It would be better coding style to write either: Foo.classMethod(); } }
Reference
http://faq.javaranch.com/view?OverridingVsHiding
Related Technologies
JEE
Technical Criterion
Programming Practices - OO Inheritance and Polymorphism
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.