Re: What do use instead of overriding static methods?
Jim T wrote:
I'm extremely new to java, so I'm sure this has been asked before.
Please bear with me. Also please pardon any typos in my pseudocode.
Coming from Objective-C land, I have a class hierarchy and a bunch of
methods that basically amount to this:
I agree with Eric. You ask for forgiveness for errors, but your errors
are so many that heck greatly impedes understanding. I can't really
tell what the heck you are after here. Some general concepts:
1. Static members are never inherited or overridden. I think that's at
least 50% of the trouble you are having right there. Java is similar to
C++ in this regard. Objective-C is off on some side road if it allows
inheritance of static members.
2. The normal way of handling this is just with regular old inheritance.
class SuperClass {
Map loadFromDatabase() {
//... load
return map;
}
}
3. If you cannot override the main method, create an overridable helper
method that you can.
class SuperClass {
final Map loadFromDatabase() {
//... load
map = loadHelper();
return map;
}
protected Map loadHelper() {
// more loading
return map;
}
}
class SubClass extends SuperClass {
protected Map loadHelper() {
// change loading behavior here
return map;
}
}
4. If you need to access a "type," you code is usually broken. Convert
access to the type into polymorphic method calls.
5. You can change the return type to a co-variant in Java 5 and later.
Co-variant means "sub-class." So if your super class has a method:
Object[] getRow() {...}
A sub-class can change this to:
String[] getRow() {...}
because String is a sub-class of Object. "getRow()" is still
overridden, not overloaded, which is usually desirable.
6. The fact that the database is the same and might be stored as a
static variable doesn't change any of the above. Accessing a static
(singleton) object doesn't change, as long as that object is thread
safe. Don't use static methods just because the variable is static, you
probably should use instance methods instead to get the correct
overriding behavior.
While I'm at it, is there any way to dynamically choose a class to
call a class method upon? Again, in objective-C, you can do:
[[self class] someClassMethod];
As Eric says, don't do this. See note 4 above: convert this selection
based on type to a polymorphic method call.
superClass.someInstanceMethod();
subClass.someInstanceMethod();