Finite values ​​of constant with inheritance in Java?

I have the following problem. I want one wide abstract type called MessageField. Using MessageField at run time should contain a String value; the rest of the type should be a connection of constant definitions and behavior. Each MessageField subclass must be a set of constant end members that define the type and, if necessary, can also override other behaviors.

So for example:

public abstract class MessageField {
   //whatever needs to go here to make this work
   //methods that define behavior
   //e.g. public int getFieldId() { return fieldId; }
}

public class TypeOne extends MessageField { 
    public final int fieldId = 1; //type defining member
    public final String tag = "->"; //type-defining member
    public String fieldValue; //freely settable/gettable
    //change any behavior if necessary
}

public class TypeTwo extends MessageField { 
    public final int fieldId = 2;
    public final String tag = "++";
    public String fieldValue;
}

public class TypeThree extends MessageField {
    public final int fieldId = 3;
    public final String tag = "blah";
    public String fieldValue;
}

fieldId . , , ? , , .

, - , , ? - , ?

!

+4
3

:

public abstract class MessageField {
    public final int fieldId;
    public final String tag;

    protected MessageField(int fieldId, String tag) {
        this.fieldId = fieldId;
        this.tag = tag;
    }

    public int getFieldId() {
        return fieldId;
    }

    public String getTag() {
        return tag;
    }
}

public class TypeOne extends MessageField {
    public String fieldValue; //freely settable/gettable

    public TypeOne() {
        super(1, "->");
    }
}

// etc.

, fieldId tag private.

+8

, , , , Factory , .

, Java, , Enum . MessageField Enum?

public enum MessageFieldType {
  public abstract int getFieldId();
  ...

  ONE {
    public int getFieldId() { return 1; }
    ...
  },
  TWO { ... }, ...
}

public class MessageField {
  public final String value;
  public final MessageFieldType fieldType;
  ...
}
+1

You can make constants confidential and use getter to access them.

public abstract class MessageField {
     private final int fieldId = 1; 
     private final String tag = "->"; 
     public int getFieldId();
}

public class TypeOne extends MessageField { 
    private final int fieldId = 1; 
    private final String tag = "->";

    public int getFieldId() {
        return fieldId;
    }
}

public class TypeTwo extends MessageField { 
    private final int fieldIdOLOLO = 2;
    private final String tag = "->"; 

    public int getFieldId() {
       return fieldIdOLOLO;
    }
}


public class TypeThree extends MessageField { 
    private final String tag = "->"; 

    public int getFieldId() {
        return 5;
    }
}
0
source

All Articles