为什么我们不应该在java中使用protected static [英] Why we should not use protected static in java
问题描述
我正在经历这个问题有没有在Java中覆盖类变量的方法是什么?
36条upvotes的第一条评论是:
I was going through this question Is there a way to override class variables in Java? The first comment with 36 upvotes was:
如果你看到的话一个
受保护的静态
,运行。
任何人都可以解释为什么是 protected static
不赞成?
Can anyone explain why is a protected static
frowned upon?
推荐答案
这比直接问题更具风格性。它表明你没有正确地思考课程的内容。
It's more a stylistic thing than a direct problem. It suggests that you haven't properly thought through what is going on with the class.
想想 static
意思是:
这个变量存在于类级别,它不是每个实例单独存在而它没有独立的存在在扩展我的课程中。
想想受保护的
意思是:
这个类可以看到这个变量,同一个包中的类和扩展我的类 。
这两个含义并不完全相互排斥,但它非常接近。
The two meanings are not exactly mutually exclusive but it is pretty close.
我可以看到你可以在哪里使用这两者的唯一情况是,如果你有一个旨在扩展的抽象类,然后扩展类可以使用原始中定义的常量修改行为。即使这样,这也是一个非常微弱的原因,因为你几乎肯定会更好地将常数公之于众。这只会让一切变得更干净,并且让人们可以更加灵活地进行分类。
The only case I can see where you might use the two together is if you had an abstract class that was designed to be extended and the extending class could then modify the behavior using constants defined in the original. Even then it's a very feeble reason though as you would still almost certainly be better having the constants as public. That just makes everything cleaner and allows the people sub classing more flexibility.
要扩展并解释第一点 - 试试这个示例代码:
To expand and explain the first point - try this example code:
public class Program {
public static void main (String[] args) throws java.lang.Exception {
System.out.println(new Test2().getTest());
Test.test = "changed";
System.out.println(new Test2().getTest());
}
}
abstract class Test {
protected static String test = "test";
}
class Test2 extends Test {
public String getTest() {
return test;
}
}
您将看到结果:
test
changed
亲自尝试: https://ideone.com/KM8u8O
类 Test2
能够从测试中访问静态成员
无需限定名称 - 但它不会继承或获取自己的副本。它正在查看完全相同的变量。 test
The class Test2
is able to access the static member test
from Test
without needing to qualify the name - but it does not inherit or get its own copy. It is looking at the exact same variable.
这篇关于为什么我们不应该在java中使用protected static的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!