Is it possible to make a static object in a parent class that subclasses will have?
Clarification:
abstract class DataPacket {
public static boolean loaded = false;
public abstract static boolean load();// Returns true if it loads. Returns false if already loaded
}
class DataPacket1 extends DataPacket {
public static boolean load() {
if (!loaded) {
// Load data
loaded = true;
return loaded;
}
return false;
}
}
class DataPacket2 extends DataPacket {
public static boolean load() {
if (!loaded) {
// Load data
loaded = true;
return loaded;
}
return false;
}
}
main() {
DataPacket1.load();// returns true
DataPacket1.load();// returns false
DataPacket2.load();// returns true
}
Is it possible to do this or something similar?
No, abstract or virtual static methods do not make sense – but you do not need it either. Simply remove the abstract
load()method fromDataPacket, and the code will work as you expect.Why does it not make sense to have virtual static methods? Because static methods are always invoked through a class reference, not through an object reference. Even though it is possible to write
foo.staticMethod(), wherefoois a variable of declared typeFoo, you are really callingFoo.staticMethod(), even iffooreally refers to an instance ofSubclassOfFoo.If you really need to call a static method based on the actual type of some object (as opposed to the declared type of the variable that refers to the object), you need to make a non-static method that calls the appropriate static method, and override it in the subclasses.