I have this code:
abstract class Entity
{
// blah-blah-blah
}
abstract class BaseCollection
{
public void add(Entity entity);
}
And I derive from the Entity and BaseCollection classes:
class User extends Entity
{
}
class UserCollection extends BaseCollection
{
public void add(User user) { // blah-blah-blah }
}
Is this an example of Liskov Substitution Principle violation? If it is, how can I solve the issue?
As
Useris a subtype ofEntityit is perfectly reasonable to add such objects toBaseCollection(viaUserCollection) — each user is anEntityPassing
UserCollectionwhereBaseCollectionis expected, will not work on the other hand: you are expecrted to be able to add anEntity, but you need aUser— or in other words: when you get an element out of theUserCollection, you might get anEntityafter this, where you expect aUser.