如何在摘要class中设置字段?

How to set fields in an abstract class?

我有一个抽象 class,里面有一个字段,它应该具有以下属性:

我现在的问题是:我该如何设置和初始化这个字段?

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;
    }
}

如何initialize/access这个字段?

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

使用受保护的构造函数之类的东西是个好主意吗?

基本满足你的需求

如果你想在创建子对象时初始化超级class字段,那么你可以调用super(val);

如果您想创建独立于父对象字段值的子对象。为子 class 使用默认构造函数,如果需要设置父值,则在子对象上调用 setField(val); 方法。

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

是的,如果您真的想限制对包中 classes 的访问