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.
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.
Good work. thanks!!
ReplyDeleteThanks Nithya :)
DeleteNice!
ReplyDeleteThanks Dhinagar
ReplyDelete