John Smith John Smith - 2 months ago 9
Java Question

Java, accessing constant it future-class? (Opposite of "super")

abstract public class Item
{
public byte getIndex()
{
return INDEX;
}
}

public class Depot extends Item
{
public static final byte INDEX = 18;
}

public class Train extends Item
{
public static final byte INDEX = 12;
}

public class Road extends Item
{
public static final byte INDEX = 6;
}


see?
Depot
has
INDEX
but
Item.getIndex()
cant reach this. Its something like opposite of "
super
", or
static::
in php.

EDIT: ok, so I can refractor this all:

abstract public class Item
{
public abstract byte getIndex();
}

public class Depot extends Item
{
public static final byte INDEX = 18;

public byte getIndex()
{
return INDEX;
}
}

public class Train extends Item
{
public static final byte INDEX = 12;

public byte getIndex()
{
return INDEX;
}
}

public class Road extends Item
{
public static final byte INDEX = 6;

public byte getIndex()
{
return INDEX;
}
}


problem: I have tons of repetitive getIndex() function.

Answer

I just wanted to see if you'd type less or more doing the things in the proper Java way.

abstract public class Item
{
    abstract public byte getIndex();
}

public class Depot extends Item
{
    public byte getIndex() { return 18; }
//  public static final byte INDEX = 18;
}

[Edited] Otherwise you'll get a nasty design pattern:

abstract public class Item
{
    static protected Map<Class<?>, Byte> indexes=new HashMap<Class<?>,Byte>();
    public byte getIndex() {
      return Item.indexes.get(this.getClass());
    }
}

public class Depot extends Item
{
    public static final byte INDEX = 18;
    static {
      Item.indexes.put(Depot.class, Depot.INDEX);
    }
}

(Just add error/exception treatment)

[Added] Or you can use introspection and pay the performance penalty at runtime (+ the fact you are denying the compiler the check if the derived really declares INDEX)

abstract public class Item
{
    public byte getIndex() {
      // this will throw *at runtime* if the derived doesn't declare INDEX
      // And, as is, it's insensitive to whether or not the
      // INDEX is static or instance field (so you need to refine your
      // verifications - see the java.lang.reflect.Field)
      return this.getClass().getField("INDEX").getByte();
    }
}

You like the alternatives better?