开发者

Best practice for class field having different values in subclasses

开发者 https://www.devze.com 2023-01-03 04:33 出处:网络
I have some abstract class, in one of its method I use a string field which is supposed to be specific to the subclasses. I wonder what is the bect practice to implemnet this? via field and setting开发

I have some abstract class, in one of its method I use a string field which is supposed to be specific to the subclasses. I wonder what is the bect practice to implemnet this? via field and setting开发者_JS百科 the field value in a consructors of the subclasses? via a static field and changing the value in every subclass?

What would you suggest?


Static fields aren't overridable, so that's not an option.

The best way is giving the superclass a constructor that takes the string as an argument, so the subclasses don't forget "filling out" the value:

abstract class Super {
    final String blah;
    protected Super(String blah) {
        if (blah == null) throw new NullPointerException();
        this.blah = blah;
    }
    public String getBlah(){ return blah; }
}
class Sub extends Super {
    public Sub() { super("Sub"); }
}


The subclasses should specify the value. The superclass should define it's interface. Use the template method design pattern.

Example:

public abstract class SuperClass {
  public abstract String getSomeValue();

  public void method() {
     String s = getSomeValue();
  }
}


public class SubClass extends SuperClass {
  private static final String CONSTANT = "";

  public String getSomeValue() {
    return CONSTANT;
  }
}

Another option is to set it in the constructor:

public abstract class SuperClass {
  private String value;

  public SuperClass(String value) {
    this.value = value;
  }
}


public class SubClass extends SuperClass {
  private static final String CONSTANT = "";

  public SubClass() {
    super(CONSTANT);
  }
}


abstract class Base{
        String field ;
        public Base(String field){
            this.field = field;
        }
    }
class Sub extends Base{
    public Sub(String field){
        super(field);
    }
}


The best practice is to define an abstract get-method at the abstract super class/interface.

This way every subclass may implement its own way to fetch the property.

abstract class SuperClass {
  abstract String getBlah();
}

class SubClass extends SuperClass{
  String getBlah(){
    return "blubb";
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消