0

Please let me know more about method hiding and what is difference between method overriding and method hiding. Thanks

for e.g.

class Test
{
    public static void m1(){}
}
class Test2 extends Test
{
    public static void m1(){}
}

Why this thing is known as method hiding but not as method overriding?

VatsalSura
  • 926
  • 1
  • 11
  • 27
  • 2
    Possible duplicate of [Why is it called "method hiding"?](http://stackoverflow.com/questions/33666148/why-is-it-called-method-hiding) – VatsalSura Jul 16 '16 at 12:13
  • 1
    Static methods can't be overriden as it is part of a class rather than an object – Unknown Jul 16 '16 at 12:21

2 Answers2

0

Have this in mind:

  • A static method belongs to the class.
  • A non-static method belongs to the object.

Now take a look at this code:

public class Test {
    public static void main(String[] args) {
        Animal d = new Dog();
        d.printStatic(); //prints "Animal"
        d.print();       //prints "Dog"
    }
}

class Animal {
    static void printStatic() {
        System.out.println("Animal");
    }
    void print() {
        System.out.println("Animal");
    }
}

class Dog extends Animal {
    static void printStatic() { 
        System.out.println("Dog");
    }
    void print() {
        System.out.println("Dog");
    }
}

The printStatic() method that is static, is hidden by the Dog class. Since static methods belong to the class, and d is declared as an Animal in the line Animal d = new Dog();, the call will refer to the method in the Animal class.

The print() method that is not static, is overriden by the Dog class. Since non-static methods belong to the object, and the d variable is pointing to a Dog, the call will refer to the method in the Dog class.

RaminS
  • 2,208
  • 4
  • 22
  • 30
0

Only instance methods (so, without the static keyword) can be overridden. So, if in a subclass, you redeclare the static method of a superclass, you don't override the static method, you declare a new static method with no relation with which of the super class.

So when you invoke the static method, the effective call method depends on which class name is prefixed before the static method invocation.

If you prefix with the super class, it's the static method of the super class which is called.

If you prefix with the subclass, it's the static method of the subclass which is called.

Personally, I find the "hiding" term not very helpful for understanding the concept.

davidxxx
  • 125,838
  • 23
  • 214
  • 215