0

I have 1 abstract class: Model<E> with 2 implementations: ItemModel and ItemLogModel. The constructor of ItemLogModel is protected, but it is still accessible from ItemModel. I expect the protected constructor to only be accessible by subclasses of ItemLogModel. Can someone explain to me why this is possible?

Code:

public abstract class Model<E> implements IModel {
    private final Repository<? extends IModel, E> _repository;
    protected E _entity;

    protected Model(Repository<? extends IModel, E> repository, E entity) 
        this._repository = repository;
        this._entity = entity;
    }        
    ...
}

public class ItemModel extends Model<Item> implements IItem {
    ...

    @Override
    public void setStatus(Status status, String logMessage) throws Exception {
        super._entity.setStatus(status.toString());
        super.update();

        // CALLING protected constructor here!
        new ItemLogModel(this, logMessage);
    }
}

public class ItemLogModel extends Model<ItemLog> implements IItemLog {

    protected ItemLogModel(ItemModel itemModel, String message) throws Exception {
        super(REPOSITORY, new ItemLog());
        super._entity.setAccessPointBean(itemModel.getEntity());
        super._entity.setStatus(itemModel.getStatus().toString());
        super._entity.setMessage(message);
        super.save();
    }

}
ivospijker
  • 702
  • 1
  • 7
  • 22
  • 4
    `protected` members are visible to the same package as well. – Peter Lawrey Jan 09 '17 at 14:00
  • @PeterLawrey okay, thanks! I did not realize that – ivospijker Jan 09 '17 at 14:01
  • 1
    Just to add reference to @PeterLawrey comment : https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.6.1 : `if the member or constructor is declared protected, then access is permitted only when one of the following is true: Access to the member or constructor occurs from within the package containing the class in which the protected member or constructor is declared. Access is correct as described in §6.6.2.` – rkosegi Jan 09 '17 at 14:05
  • Here's a [good table](http://stackoverflow.com/a/33627846/276052) illustrating the scope of protected. – aioobe Jan 09 '17 at 14:58

0 Answers0