在java中覆盖静态的替代方法 [英] Alternative to overiding static in java
问题描述
我想知道:将属性拟合到属于大型继承结构的类的最佳方法是什么.我想创建一个抽象的静态方法,每个类都会覆盖该方法,但是经过一个似乎不起作用的快速谷歌.有什么建议?
我可以把它变成一个实例方法,但它确实是一个类级别的规范.
提前致谢.
我建议你创建一个抽象方法,就像你想到的那样,让这个方法在每个类的静态变量中实现.
>
抽象类 Base {抽象字符串 getValue();}A 类扩展 Base {静态字符串 aValue = "来自 A";字符串 getValue() {返回一个值;}}B 类扩展 A {静态字符串 bValue = "来自 B";字符串 getValue() {返回 b 值;}}
它需要在每个类中多一点样板,而不仅仅是一个字段声明,但我相信很难做任何事情.
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.
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.
这篇关于在java中覆盖静态的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!