1

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?

Stas Jaro
  • 4,747
  • 5
  • 31
  • 53

3 Answers3

3

Static methods cannot be abstract or virtual in Java (which makes sense when you consider the way Java does dispatch through vtables). What you should do is create an instance, and make it a singleton.

Considering the way you access load(), you do not need polymorphic behavior. Perhaps your real case is more complicated, but your snippet does not show a need for polymorphism.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

No, abstract or virtual static methods do not make sense - but you do not need it either. Simply remove the abstract load() method from DataPacket, 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(), where foo is a variable of declared type Foo, you are really calling Foo.staticMethod(), even if foo really refers to an instance of SubclassOfFoo.

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.

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81
0

Static methods are not inheritable because they belong to the class and not to individual objects. Hence code will not compile.

Bhushan
  • 18,329
  • 31
  • 104
  • 137