I'm creating a Mario clone where everything on the screen is an instance of ScreenElement. A ScreenElement is Landable if it can be landed on by Mario.
public class ScreenElement { public boolean isLandable() { return false; } } Some classes override isLandable, for example:
public class GrassBlock extends ScreenElement { @Override public boolean isLandable() { return true; } } And classes that don't override isLandable should inherit it from the closest super class that does. That is to say, I need polymorphism. Now this all works fine as long as isLandable is an instance method. However whether or not a given ScreenElement is Landable depends on the class, not the instance. So isLandable should really be static. But if I make it static, I cannot override it or inherit in sub classes that don't explicitly define it. Is there a simple workaround to this problem.
EDIT: I do realize that the way I have it set up right now, it is working correctly but the reason I am bringing this up is because I have encountered a problem. Given a class that extends ScreenElement, I need to find out the result of isLandable. The only thing I could think of was this:
private <S extends ScreenElement> boolean isThisLandable(Class<S> category) { return category.newInstance().isLandable(); } I have to create a new instance to figure out something that doesn't depend on the instance, and this seems unnatural.
EDIT 2: Here's the specific piece of code that I'm dealing with.
private <S extends ScreenElement> S getGenericScreenElement(Mario mario, Class<S> category) { for (ScreenElement element : screenElements) { if (category.isInstance(element)) { S elementToTest = category.cast(element); if (elementToTest.isLandable()) { //return elementToTest if it matches additional criteria } } } return null; }
LandableElementclass that inheritsScreenElementand is inherited by landable elements? Then you can override the method inLandable Elementor alternatively just useinstanceof LandableElementto check if objects are landable.instanceofis probably not the best advice; in general or otherwise.isLandablea second time to set it back to false.instanceofthis or that, there's, with little exception, a better design. One that will improve your code and life.