nhouser9 nhouser9 - 3 months ago 8
Java Question

Override a property in Java

In Java, I have had several projects recently where I used a design pattern like this:

public abstract class A {
public abstract int getProperty();
}

public class B extends A {
private static final int PROPERTY = 5;

@Override
public int getProperty() {
return PROPERTY;
}
}


Then I can call the abstract method
getProperty()
on any member of class
A
. However, this seems unwieldy - it seems like there should be some way to simply override the property itself to avoid duplicating the
getProperty()
method in every single class which extends
A
.

Something like this:

public abstract class A {
public static abstract int PROPERTY;
}

public class B extends A {
@Override
public static int PROPERTY = 5;
}


Is something like this possible? If so, how? Otherwise, why not?

Answer

You cannot "override" fields, because only methods can have overrides (and they are not allowed to be static or private for that).

You can achieve the effect that you want by making the method non-abstract, and providing a protected field for subclasses to set, like this:

public abstract class A {
    protected int propValue = 5;
    public int getProperty() {
        return propValue;
    }
}

public class B extends A {
    public B() {
        propValue = 13;
    }
}

This trick lets A's subclasses "push" a new value into the context of their superclass, getting the effect similar to "overriding" without an actual override.

Comments