Search code examples
javaoopmethodsfieldabstract

Why not abstract fields?


Why can't Java classes have abstract fields like they can with abstract methods?

For example: I have two classes that extend the same abstract base class. These two classes each have a method that is identical except for a String constant, which happens to be an error message, within them. If fields could be abstract, I could make this constant abstract and pull the method up into the base class. Instead, I have to create an abstract method, called getErrMsg() in this case, that returns the String, override this method in the two derived classes, and then I can pull up the method (which now calls the abstract method).

Why couldn't I just make the field abstract to begin with? Could Java have been designed to allow this?


Solution

  • 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.