问题描述
我正在阅读 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?
推荐答案
静态方法不是很面向对象的一个到目前为止还没有提到的原因是接口和抽象类只定义了非静态方法.因此静态方法不太适合继承.
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.
这篇关于为什么静态方法不被视为良好的面向对象实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!