Why not abstract fields? Why not abstract fields? java java

Why not abstract fields?


You can do what you described by having a final field in your abstract class that is initialised in its constructor (untested code):

abstract class Base {    final String errMsg;    Base(String msg) {        errMsg = msg;    }    abstract String doSomething();}class Sub extends Base {    Sub() {        super("Sub message");    }    String doSomething() {        return errMsg + " from something";    }}

If your child class "forgets" to initialise the final through the super constructor the compiler will give a warning an error, just like when an abstract method is not implemented.


I see no point in that. You can move the function to the abstract class and just override some protected field. I don't know if this works with constants but the effect is the same:

public abstract class Abstract {    protected String errorMsg = "";    public String getErrMsg() {        return this.errorMsg;    }}public class Foo extends Abstract {    public Foo() {       this.errorMsg = "Foo";    }}public class Bar extends Abstract {    public Bar() {       this.errorMsg = "Bar";    }}

So your point is that you want to enforce the implementation/overriding/whatever of errorMsg in the subclasses? I thought you just wanted to have the method in the base class and didn't know how to deal with the field then.


Obviously it could have been designed to allow this, but under the covers it'd still have to do dynamic dispatch, and hence a method call. Java's design (at least in the early days) was, to some extent, an attempt to be minimalist. That is, the designers tried to avoid adding new features if they could be easily simulated by other features already in the language.