Search code examples
javaconstructorabstractfinal

Final variables in abstract classes


In Java, I can't create instances of abstract classes. So why doesn't eclipse scream about the following code?

public abstract class FooType {
    private final int myvar;

    public FooType() {
        myvar = 1;
    }
}

Solution

  • The code is fine, the final variable is initialized in the constructor of FooType.

    You cannot instantiate FooType because of it being abstract. But if you create a non abstract subclass of FooType, the constructor will be called.

    If you do not have an explicit call to super(...) in a constructor, the Java Compiler will add it automatically. Therefore it is ensured that a constructor of every class in the inheritance chain is called.