Search code examples
javaabstract-classstatic-methods

How to store static data about a class to


Imagine I have an abstract class like this:

public abstract class Device {

  public Device(DeviceModel model){
    // ...
  }

  public abstract boolean isBuildable();
}

Then I have an implementation of it that might look like this:

public final class Floor extends Device {
  // ...

  @Override
  public void boolean isBuildable(){
    return false;
  }
}

Here, each Device subclass returns either true or false to #isBuildable(). But each instance of Floor always returns false. Another implementation of Device may return true. That sounds like a static data : it does not depends on the current instance, but on the type of the Device.

Currently, I'm creating an instance of the class to get its value, as #isBuildable() isn't static. But I think that's poor code design.

So, what I'm trying to achieve here is like creating abstract static method. I've seen this question that doesn't help so much. I would forces the implementation of #isBuildable (this time as static) in all subclasses of Device, so that I can invoke Floor.isBuildable() or something else of the same kind.

Here I can't control all the source, so I can't use reflectivity on that. Hope you understand this weird question !


Solution

  • If you need to store class-specific (not instance-specific) information, custom annotations may be the way to go.

    This require a function using reflection to access that piece of information, which could be overkill in a small project, but should be no problem in a larger framework or similar project.