In a Java program, I have multiple subclasses inheriting from a parent (which is abstract). I wanted to express that every child should have a member that is set once only (which I was planning to do from the constructor). My plan was to code s.th. like this:
public abstract class Parent {
protected final String birthmark;
}
public class Child extends Parent {
public Child(String s) {
this.birthmark = s;
}
}
However, this seems to not please the Java gods. In the parent class, I get the message that birthmark
"might not have been initialized", in the child class I get "The final field birthmark
cannot be accessed".
So what's the Java way for this? What am I missing?
I would do it like this:
final means that the variable can be initialized once per instance. The compiler isn't able to make sure that every subclass will provide the assignment to birthmark so it forces the assignment to happen in the constructor of the parent class.
I added the checking for null just to show that you also get the benefit of being able to check the arguments in one place rather than each cosntructor.
You probably want to have a Parent(String birthmark) constructor so that you can ensure in your Parent class that final is always initialized. Then you can call super(birthmark) from your Child() constructor.