0

Need an advice on how to achieve decoupling of UI graphs from content.

Preamble:

I have an abstract Sensor interface and a bunch of implementations. Interface defines a couple of functions, such as parsing text to actual values, etc.

On the other hand, each Sensor implementation has it's own defined maximum range, which is final constant (and, in sense, static). On the user interface I would like to draw graphs of incoming Sensor data. Each graph has to have default Y range set to maximum range of the particular implementation.

Actual question

Is there a way of accessing static fields of implementations via abstract superclass or interface without actually instantiating a dummy object of specific implementation type?

  • Static members of a class are accessed by prefixing the member with the class name, as in MyClass.Member; no dummy object required. See caveofprogramming.com/java/… – Robert Harvey Sep 8 '17 at 20:11
  • I would like to access them via interface or superclass method, to avoid sprinkling code with typecasting – stiebrs Sep 8 '17 at 20:32
  • Can't be done, unless you're prepared to do something really exotic like reflecting over the class definitions. – Robert Harvey Sep 8 '17 at 20:38
  • 3
    Why not just add another method to the Sensor interface something like maxRange(). Then each class must implement it and can return the final constant. Now you are coding to the interface not the implementation, and in the future you may have a class where each instance has a different max and that doesn't break the Sensor contract. – Hangman4358 Sep 9 '17 at 19:02
1

Static methods in Java are not for abstract access.

In some languages we have true metaclasses, meaning that classes themselves are represented by full-fledged instances. Metaclasses can house class (i.e. static in Java) methods & fields but (unlike Java with statics) they can also participate in class hierarchy, meaning we can create abstraction over several metaclass instances (i.e. over several regular classes).

In Java, we don't have that so if you want abstraction at the class level, we just use other regular classes that are more loosely associated (rather than specifically one class being the metaclass for another class).

Given Java, there are three choices, I think. Use statics without abstraction, conflate this capability with another existing abstraction already in your design, or create another separate but related abstraction for this, say one that represents configuration, or a metaclass, or factory, or something else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.