为什么我们不应该在 Java 中使用 protected static [英] Why we should not use protected static in java

查看:43
本文介绍了为什么我们不应该在 Java 中使用 protected static的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究这个问题 是否有在 Java 中覆盖类变量的方法?获得 36 票的第一条评论是:

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是什么意思:

这个变量存在于类级别,它不会为每个实例单独存在,并且它在扩展我的类中没有独立存在.

This variable exists at class level, it does not exist separately for each instance and it does not have an independent existence in classes which extend me.

想想什么是protected:

这个变量可以被这个类、同一个包中的类以及扩展我的类看到.

This variable can be seen by this class, classes in the same package and classes which extend me.

这两种含义并不完全相互排斥,但非常接近.

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. That sort of arrangement would most likely end up very messy though and indicates weakness in the design of the classes.

在大多数情况下,将常量设为公开会更好,因为这只会让一切变得更干净,并允许人们更灵活地进行子类化.撇开别的不说,在很多情况下,组合比继承更可取,而抽象类则强制继承.

In most cases it would be better to have the constants as public since that just makes everything cleaner and allows the people sub-classing more flexibility. Quite apart from anything else in many cases composition is preferable to inheritance, while abstract classes force inheritance.

要查看这如何破坏事物的一个示例并说明我所说的变量不具有独立存在的含义,请尝试以下示例代码:

To see one example of how this could break things and to illustrate what I mean by the variable not having an independent existence 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 访问静态成员 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 object in memory.

这篇关于为什么我们不应该在 Java 中使用 protected static的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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