为什么静态方法不是好的OO实践? [英] Why aren't static methods considered good OO practice?

查看:143
本文介绍了为什么静态方法不是好的OO实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读编程Scala 。在第4章开头,作者评论说Java支持静态方法,这是不那么纯粹的OO概念。为什么是这样?

I'm reading Programming Scala. At the beginning of chapter 4, the author comments that Java supports static methods, which are "not-so-pure OO concepts." Why is this so?

推荐答案

到目前为止还没有提到的静态方法不是很多OO的一个原因是接口和抽象类只定义非静态方法。静态方法因此不适合继承。

One reason that static methods aren't very OO that hasn't been mentioned so far is that interfaces and abstract classes only define non-static methods. Static methods thus don't fit very well into inheritance.

还要注意,静态方法无法访问 super ,这意味着静态方法不能在任何实际意义上被覆盖。其实,他们根本不能被覆盖,只有隐藏。尝试这样:

Note also that static methods do not have access to "super", which means that static methods cannot be overridden in any real sense. Actually, they can't be overridden at all, only hidden. Try this:

public class Test {
    public static int returnValue() {
        return 0;
    }

    public static void main(String[] arg) {
        System.out.println(Test.returnValue());
        System.out.println(Test2.returnValue());
        Test x = new Test2();
        System.out.println(x.returnValue());
    }
}


public class Test2 extends Test {
    public static int returnValue() {
        return 1;
    }
}

当你运行这个,你不会得到什么你期望 Test.returnValue()给出你的期望。 Test2.returnValue() 隐藏超类中同名的方法(它不会覆盖它),它给出了你期望的。

When you run this, you won't get what you expect. Test.returnValue() gives what you expect. Test2.returnValue() hides the method of the same name in the superclass (it does not override it), and it gives what you would expect.

可能天真地期望非静态调用静态方法来使用多态。没有变量被声明的任何类是用于查找该方法的类。这是错误的形式,因为有人可能希望代码与实际操作不同。

One might naively expect "non-statically" calling a static method to use polymorphism. It doesn't. Whatever class the variable is declared as is the one used to look up the method. This is bad form because someone might expect the code to do something different from what it actually does.

这并不意味着不要使用静态方法!这意味着您应该为那些真正希望Class对象拥有该方法的实例保留使用静态方法,而不仅仅是作为一个单独的懒惰方式。

This doesn't mean, "Don't use static methods!" It does mean that you should reserve use of static methods for those instances where you really want the Class object to own the method, and not just as a lazy way of making a singleton.

这篇关于为什么静态方法不是好的OO实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆