3 September 2017

Method Overriding VS Method Hiding

We Know that the Polymorphism is of two types
1.Static
2.Dynamic

In Dynamic Polymorphism the method which executes will be decided based on the object stored in the reference variable.

This is regarding instance methods

public class Animal {
    public void foo() {
        System.out.println("Animal");
    }
}

public class Cat extends Animal {
    public void foo() { // overrides Animal.foo()
        System.out.println("Cat");
    }
}

Then the following will happen:

class Test{

public static void main(String args[]){
Animal a = new Animal();
Animal b = new Cat();
Animal c = new Cat();
Animal d = null;

a.foo(); // prints Animal
b.foo(); // prints Cat
c.foo(); // prints Cat
d.foo(): // throws NullPointerException
    }
}

Instance methods, which are polymorphic and are thus overridden. The method called depends on the concrete, run time type of the object:

But for static methods it won't work.
The static methods will executes as follows....

public class Animal {
    public static void foo() {
        System.out.println("Animal");
    }
}

public class Cat extends Animal {
    public static void foo() { // overrides Animal.foo()
        System.out.println("Cat");
    }
}

class Test{

public static void main(String args[]){
Animal a = new Animal();
Animal b = new Cat();
Cat c = new Cat();
Animal d = null;

a.foo(); // prints Animal
b.foo(); // prints Animal
c.foo(); // prints Cat
d.foo(): // throws NullPointerException
      }
}

Here, Cat.foo() is said to hide Animal.foo(). Hiding does not work like overriding, because static methods are not polymorphic.
This is called Method Hiding Concept.

Calling static methods on instances rather than classes is a very bad practice, and should never be done.

JAVA SetUp in System

JAVA ENVIRONMENT SET UP  =========================== In System Variables JAVA_HOME : C:\Program Files\Java\jdk1.8.0_144 JDK_HOME  : %J...