Method Hiding in java

“Method hiding means subclass has defined a class method with the same signature as a class method in the superclass. In that case the method of superclass is hidden by the subclass.”

public class Super {
public static void foo() {
System.out.println(“Super”);
}
}
public class Child extends Super {
public static void foo() {  // hides Super.foo()
System.out.println(“Child”);
}
}
Here, Child.foo() is said to hide Super.foo().
static methods are not polymorphic

Super.foo(); // prints Super
Child.foo(); // prints Child

Lets examing on non-static scope

Super a = new Super();
Super b = new Child();
Child c = new Child();
Super d = null;

a.foo(); //  Prints Super
b.foo(); //  Prints Super because the declared type of b is Super
c.foo(); //  Prints Child because the declared type of c is Child
d.foo(); //  Prints Super because of static method

if the methods are nonstatic  in Super and child classes then

Super a = new Super();
Super b = new Child();
Child c = new Child();
Super d = null;

a.foo(); // prints Super
b.foo(); // prints Child–> Observe and compare this method call on static and non-                                                                                                                                    static scenarios
c.foo(); // prints Child
d.foo(): // throws NullPointerException

2 thoughts on “Method Hiding in java

  1. some important point to observe. if the methods are static, then declaring and instantiating the object to null, and invoking the static method does not leads to null pointer exception. usually we will be in opinion invoking a reference variable which is null breaks to null pointer exception

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s