I’ve defined a class, and I’d like to have a class method (or variable, I don’t really care) which needs to be overriden by each inherited class. My best approaches have been unsuccessful:
public abstract String getHumanString();, as abstract methods can’t be static
public static String getHumanString();, as static methods can only be hidden, not overriden.
I don’t know if there is another trick I could use. I could also be happy to automatically define getHumanString() by myself on the parent class with something like humanize(class.getClass().getName()) (I’d just make getName() look more beautiful, according to my needs), getName() is not accessible on static methods. So, to sum up, my question is:
1. Can I have a static method/variable which could be edited on subclasses?
OR, as another valid solution:
2. Can I create a static method that plays with its own class name?
Thanks in advance.
EDIT:
Imagine this situation (I’ll skip useless lines, as I’m directly writing code here):
class ParentClass {
public static (or whatever) String getHumanString() {
return "My Parent Class";
}
public static showMyInfo() {
System.out.println(getHumanString());
}
}
class ChildClass {
@Override
public static (or whatever) String getHumanString() {
return "My Child Class";
}
}
…
public static void main()
{
ChildClass.showMyInfo();
}
It should output (as I’d want) “My Child Class”, but it actually outputs (as you all know) “My Parent Class”.
Have a properties file, with class name as key and human string as value. And a single static method somewhere to read it.
Also lends itself to localization if necessary. Plus you can “enhance” existing classes whose definition you cannot change.