Search code examples
javamethod-hidingdata-hiding

Instance & Method Hiding: The Point Is?


Can someone please explain the reason and benefit for instance and method hiding, in particular what advantage would I gain duplicating superclass members? Doesn't that fly in the face of inheritance whose purpose is to further define a class and improve upon it?


Solution

  • I strongly disagree. As elements can only be hidden when they're static, it doesn't make a difference, if you're using the good practice of calling static elements by its declaring class and not by its subclasses or instances.

    As the example taken from the Java tutorials page

    public class Animal {
        public static void testClassMethod() {
            System.out.println("The static method in Animal");
        }
        public void testInstanceMethod() {
            System.out.println("The instance method in Animal");
        }
    }
    
    public class Cat extends Animal {
        public static void testClassMethod() {
            System.out.println("The static method in Cat");
        }
        public void testInstanceMethod() {
            System.out.println("The instance method in Cat");
        }
    
        public static void main(String[] args) {
            Cat myCat = new Cat();
            Animal myAnimal = myCat;
            Animal.testClassMethod();
            myAnimal.testInstanceMethod();
        }
    }
    

    Will output

    The static method in Animal
    The instance method in Cat
    

    As you can see, even with another static method implemented with the same name, the one declared in Animal wasn't really hidden, unless you call Cat.testClassMethod(); and expect the same result.

    It's just a question of abstracting the idea of inheritance here, because static elements aren't really inherited, just acessible to the subclass.