Java: Initializing a public static field in superclass that needs a different value in every subclas

Posted by BinaryMuse on Stack Overflow See other posts from Stack Overflow or by BinaryMuse
Published on 2010-04-14T20:42:50Z Indexed on 2010/04/14 20:53 UTC
Read the original article Hit count: 305

Filed under:
|
|
|
|

Good evening,

I am developing a set of Java classes so that a container class Box contains a List of a contained class Widget. A Widget needs to be able to specify relationships with other Widgets. I figured a good way to do this would be to do something like this:

public abstract class Widget {
    public static class WidgetID {
        // implementation stolen from Google's GWT
        private static int nextHashCode;
        private final int index;

        public WidgetID() {
            index = ++nextHashCode;
        }

        public final int hashCode() {
            return index;
        }
    }

    public abstract WidgetID getWidgetID();

}

so sublcasses of Widget could:

public class BlueWidget extends Widget {
    public static final WidgetID WIDGETID = new WidgetID();

    @Override
    public WidgetID getWidgetID() {
        return WIDGETID;
    }
}

Now, BlueWidget can do getBox().addWidgetRelationship(RelationshipTypes.SomeType, RedWidget.WIDGETID, and Box can iterate through it's list comparing the second parameter to iter.next().getWidgetID().

Now, all this works great so far. What I'm trying to do is keep from having to declare the public static final WidgetID WIDGETID in all the subclasses and implement it instead in the parent Widget class. The problem is, if I move that line of code into Widget, then every instance of a subclass of Widget appears to get the same static final WidgetID for their Subclassname.WIDGETID. However, making it non-static means I can no longer even call Subclassname.WIDGETID.

So: how do I create a static WidgetID in the parent Widget class while ensuring it is different for every instance of Widget and subclasses of Widget? Or am I using the wrong tool for the job here?

Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about static