Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, why can't I declare a final member (w/o initializing it) in the parent class and set its value in the subclass? How can I work around?

Tags:

java

final

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?

like image 423
Hanno Fietz Avatar asked Mar 19 '09 18:03

Hanno Fietz


3 Answers

You can't do it because while comparing the parent class, the compiler can't be sure that the subclass will initialize it. You'll have to initialize it in the parent's constructor, and have the child call the parent's constructor:

public abstract class Parent {
    protected final String birthmark;
    protected Parent(String s) {
        birthmark = s;
    }
}

public class Child extends Parent {
    public Child(String s) {
        super(s);
        ...
    }
}
like image 133
Adam Rosenfield Avatar answered Oct 09 '22 01:10

Adam Rosenfield


Pass it to the parent constructor:

public abstract class Parent {
    private final String birthmark;
    public Parent(String s) {
        birthmark = s;
    }
}

public class Child extends Parent {
    public Child(String s) {
        super(s);
    }
}
like image 23
McDowell Avatar answered Oct 09 '22 01:10

McDowell


Another Java-ish way to do this is probably to have the parent class to define an abstract "getter", and have the children implement it. It's not a great way to do it in this case, but it in some cases it can be exactly what you want.

like image 2
Paul Tomblin Avatar answered Oct 09 '22 03:10

Paul Tomblin