简体   繁体   English

为什么在Java中隐藏了不好的做法

[英]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 ? 我同意应该通过类Name而不是对象引用来调用静态变量和方法,以使代码易于理解,但是为什么不鼓励这种隐藏行为呢?

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 . 我实际上对这里的文档非常满意(感谢@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? 还要从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." 甚至JavaDoc的解释也令人困惑 :“在实例而不是类上调用静态方法是非常糟糕的做法,绝不应该这样做。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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