Method Hiding - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Thursday, June 30, 2016

Method Hiding

What is method hiding?

Method hiding means when the subclass has defined the class method with the same signature(name, plus the number and the type of its parameters) as a class method of the superclass. It means the method of superclass is hidden by subclass method. The method will not be called according to the type of object referred, but according to the type of reference. In other words, static functions are resolved early, at compile time.

Now we will understand method hiding with an example.

public class Foo {
      public static void methodName() {  
           System.out.println("Method of Foo class called");  
      }
 }

public class Bar extends Foo {
 public static void methodName() {
  System.out.println("Method of Bar class called");
 }
}

public class TestMethodHiding {

 public static void main(String[] args) {

  Foo foo1 = new Foo();
  Bar bar1 = new Bar();
  Foo foo2 = new Bar();
  Foo foo3 = null;

  foo1.methodClassName(); // Static method of Foo class called
  foo2.methodClassName(); // Static method of Foo class called
  foo3.methodClassName(); // Static method of Foo class called

  bar1.methodClassName(); // Static method of Bar class called
 }
}

Accessing static methods on instance rather than Classes is very bad practice, should never be done.

Static methods should always access in a static way.


Note: A hiding method can also return a subtype of the type returned by the hidden method. This subtype is called as covariant return type.

There is two type of polymorphism; Method overloading and Method overriding, as soon as the method overriding turn into Method Hiding, it loses polymorphism features.

4 comments :