Java:抽象类中的静态字段 [英] Java: static field in abstract class

查看:31
本文介绍了Java:抽象类中的静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是从一个例子开始,它最好地解释了它:

I just start out with an example, that explains it best:

public abstract class A{
    static String str;
}

public class B extends A{
    public B(){
        str = "123";
    }
}

public class C extends A{
    public C(){
        str = "abc";
    }
}

public class Main{

    public static void main(String[] args){
        A b = new B();
        A c = new C();
        System.out.println("b.str = " + b.str);
        System.out.println("c.str = " + c.str);
    }
}

这将打印出来:

b.str = abc

b.str = abc

c.str = abc

c.str = abc

但我想要一个解决方案,其中实例化超类的每个子类都有自己的自己的类变量,同时我希望能够通过标识符引用该类变量,或者一个方法调用,在抽象超类中定义.

But I would like a solution where each subclass that instantiate the super class, has their own class variable, at the same time I want to be able to reference that class variable through the identifier, or a method call, defined in the abstract super class.

所以我希望输出是:

b.str = 123

b.str = 123

c.str = abc

c.str = abc

这可行吗?

推荐答案

如果您希望类 B 和 C 具有单独的静态变量,则需要在这些类中声明变量.基本上,静态成员和多态性不会结合在一起.

If you want classes B and C to have separate static variables, you'll need to declare the variables in those classes. Basically, static members and polymorphism don't go together.

请注意,就可读性而言,通过引用访问静态成员确实是一个坏主意 - 它看起来就像它取决于引用的值,当它真的没有.因此,当您将 str 向下移动到 B 和 C 时,您当前的代码甚至无法编译.相反,您需要

Note that accessing static members through references is a really bad idea in terms of readability - it makes it look like it depends on the value of the reference, when it doesn't really. So your current code won't even compile when you've moved str down to B and C. Instead, you'll need

System.out.println("b.str = " + B.str);
System.out.println("c.str = " + C.str);

如果你真的需要多态地访问值(即通过 A 的实例),那么一个选择是创建一个多态的 getter:

If you really need to access the value polymorphically (i.e. through an instance of A) then one option is to make a polymorphic getter:

public class A {
    public abstract String getStr();
}

public class B extends A {
    private static String str = "b";

    @Override public String getStr() {
        return str;
    }
}

(对于 C 也是如此).

(and the same for C).

这样您就可以获得您想要的行为,因为每个实例没有单独的变量,但您仍然可以多态地使用它.实例成员返回这样的静态值有点奇怪,但是您使用的是类型多态性的值,基本上......

That way you get the behaviour you want in terms of not having a separate variable per instance, but you can still use it polymorphically. It's a little odd for an instance member to return a static value like this, but you're using the value for polymorphism of type, basically...

这篇关于Java:抽象类中的静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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