Overriding vs Hiding Java - Confused

This is the difference between overrides and hiding,

  1. If both method in parent class and child class are an instance method, it called overrides.
  2. If both method in parent class and child class are static method, it called hiding.
  3. One method cant be static in parent and as an instance in the child. and visa versa.

enter image description here


Static methods are hidden, non-static methods are overriden. The difference is notable when calls are not qualified "something()" vs "this.something()".

I can't really seem to put it down on words, so here goes an example:

public class Animal {

    public static void something() {
        System.out.println("animal.something");
    }

    public void eat() {
        System.out.println("animal.eat");
    }

    public Animal() {
        // This will always call Animal.something(), since it can't be overriden, because it is static.
        something();
        // This will call the eat() defined in overriding classes.
        eat();
    }

}


public class Dog extends Animal {

    public static void something() {
        // This method merely hides Animal.something(), making it uncallable, but does not override it, or alter calls to it in any way.
        System.out.println("dog.something");
    }

    public void eat() {
        // This method overrides eat(), and will affect calls to eat()
        System.out.println("dog.eat");
    }

    public Dog() {
        super();
    }

    public static void main(String[] args) {
        new Dog();
    }

}

OUTPUT:

animal.something
dog.eat

Overriding basically supports late binding. Therefore, it's decided at run time which method will be called. It is for non-static methods.

Hiding is for all other members (static methods, instance members, static members). It is based on the early binding. More clearly, the method or member to be called or used is decided during compile time.

In your example, the first call, Animal.testClassMethod() is a call to a static method, hence it is pretty sure which method is going to be called.

In the second call, myAnimal.testInstanceMethod(), you call a non-static method. This is what you call run-time polymorphism. It is not decided until run time which method is to be called.

For further clarification, read Overriding Vs Hiding.