Search code examples
javainheritanceconstructorprivateprotected

Protected member Vs private member in inheritance java


I have an abstract class Entity and then multiple instance can extend Entity

like

A extends Entity {
}
B extends Entity {
}

Now all the entity needs to have entityId

So should I have entityId as a private field in Entity and set it via the constructor, or as a protected member in Entity, so that the subclasses can access it directly?


Solution

  • First off, you can rename entityId as id as it is obviously the id of the entity. It is a member of Entity.

    I will assume that id cannot be changed and as such it should be private, set only once and only in the constructor. The class should have a public getId() method. This way other objects can access it in addition to subclasses.

    With this implementation id can't be changed accidentally by subclasses.