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?

有帮助吗?

解决方案

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.

其他提示

In Java method hiding happens when static methods with identical signatures are defined in classes related through inheritance. It does not happen to instance methods, which produce an override in this situation.

Java language designers needed to assign one of two possible semantics to it - the choices were to hide or to override the static method.

I think the reason why they went with hiding is that it is much easier to understand and to implement. It also has a strong potential of improving performance, because the dispatch of static methods could be done at compile time.

Overall, this wasn't a big deal, because you have access to the hidden methods as well, as long as you specify the class name where the hidden static method is defined.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top