在Java中替代static的替代方法 [英] Alternative to overiding static in java
问题描述
我想知道:将属性拟合到属于大型继承结构的类的最佳方法是什么?我想制作一个抽象的静态方法,每个类都可以重写该方法,但是在经过快速谷歌搜索后似乎无效。有什么建议么?
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.
请先谢谢。
推荐答案
我建议您按照您的想法创建一个抽象方法,并按照以下方式实现该方法:
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中替代static的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!