Alternative to overiding static in java

你。 提交于 2019-12-10 16:15:13

问题


I was wondering: what would be the best way to fit an attribute to a class which is part of a large inheritance structure. I wanted to make an abstract static method which each class would override but after a quick google that doesn't seem to work. Any suggestions?

I could make it an instance method but it really is a class level specification.

Thanks in advance.


回答1:


I would suggest you create an abstract method, just as you have thought of, and let this method be implemented in terms of static variables in each class.

abstract class Base {
    abstract String getValue();
}

class A extends Base {

    static String aValue = "From A";

    String getValue() {
        return aValue;
    }
}

class B extends A {

    static String bValue = "From B";

    String getValue() {
        return bValue;
    }
}

It requires a little bit more boiler plate in each class, than just a field declaration, but I believe it is hard to do anything about that.



来源:https://stackoverflow.com/questions/10718004/alternative-to-overiding-static-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!