Search code examples
javaabstractaccess-modifiers

How to set fields in an abstract class?


I have an abstract class with a field in it, which should have following properties:

  • readonly for the public interface
  • writeonly for the subclasses

My question now is: how should I set and initialize this field?

public abstract class A {
    // initialize it here ?
    private int field = 0;

    // initialize it in constructor ?
    protected A(int field)
    {
        this.field = field;
    }
      
    // use protected setter ?
    protected void setField(int val){
        this.field = val;
    }

    // or use protected field
    protected int field;

    public int getField(){
        return field;
    }
}

How to initialize/access this field?

public class B extends A {
    
    public B(int val){
        super(val);
        // or
        setField(val);
        // or
        field = val;
    }
}

and is it a good idea to use something like a protected constructor?


Solution

  • It's basically on your need

    If you want to initialize super class field at the creation of child object it self, then you could call super(val);

    If you want to create your child object independent of parent object's field values. use Default contructor for child class and if required to set parent value call setField(val); method on child object.

    is it a good idea to use smth. like a protected constructor ?

    Yes if you really want to restrict access for the classes within the package