简体   繁体   中英

Why is hiding a bad practice in Java

Well, the question is not what is method or variable hiding. The question is why is it discouraged to use it.

If some one is clear of static and dynamic binding , everything seems logical. I agree that static variables and methods should be called by class Name and not by object reference to make code easy to understand , but why is this practice of hiding discouraged ?

Is it just because so that code becomes even more easier to read or is it some thing else ?

It dont make a lot of sense to do overriding of a static method, because the overriding was though for polymorphism things, but you are not manipulating objects but classes instead when you´r calling the method. So it could take you to execute it in a non-static way and you would be subject to the type of the declared variable and NOT the instance of it.

I'm actually pretty happy with the docs here (thanks @baao): https://docs.oracle.com/javase/tutorial/java/IandI/override.html .

Note the difference between hiding and overriding: - Hiding refers to a static method in a subclass with the same signature as the static method in the superclass and is considered bad practice - Overriding is what allows subclasses to modify inherited behavior, and is not bad practice.

I'll use the example again from the docs:

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;
        myAnimal.testClassMethod();
        // "The static method in Animal"
        myAnimal.testInstanceMethod();
        // "The instance method in Cat"
    }
}

To quote another answer as well from What is method hiding in Java? Even the JavaDoc explanation is confusing : "Calling static methods on instances rather than classes is a very bad practice, and should never be done."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM