1

I Have a UserEntity class which implements the IUserEntity interface.

In the UserEntity class I have a static map:

private static Map<IUserEntity.IIdentifiable, IUserEntity> staticUserEntityMap = new HashMap<>();

In the IUserEntity interface I would like to write a method like that:

public Collection<IUserEntity>      getUsers();

And in the class :

public static Collection<IUserEntity> getUsers(){
    return staticUserEntityMap.values();
}

But I can't declare static methods in the interface and I can't change the method signature in the UserEntity class.

How can I do this ?

Caleb Kleveter
  • 11,170
  • 8
  • 62
  • 92
Maxime Gajovski
  • 79
  • 1
  • 1
  • 6

3 Answers3

3

In Java 8 you can have default implementations in interface but I believe that will not solve your problem. Instead of changing the method signatures you can create a separate static method and call it with the class name within getUsers implementation. e.g.

Create new method:

public static Collection<IUserEntity> getUsersStatic() {
   return staticUserEntityMap.values();
}

Call this method from getUsers:

public Collection<IUserEntity>      getUsers() {
  return UserEntity.getUsersStatic();
}
Gaël J
  • 11,274
  • 4
  • 17
  • 32
Riaz
  • 104
  • 4
  • Huummmm, Then i have to do this for all CRUD methods if i want to implements those ? And each UserEntity object have access to those "static" methods isn't bad ? – Maxime Gajovski Dec 26 '15 at 14:13
2

I'd refer you to this question, and the docs:

In addition to default methods, you can define static methods in interfaces. (A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.) This makes it easier for you to organize helper methods in your libraries; you can keep static methods specific to an interface in the same interface rather than in a separate class.

You could, however, implement the field in the interface as well, as that would allow you to implement your simple static method. Downside would be that the Map would become public. It'd look like this:

public interface  IUserEntity {
// ...

 static Map<IUserEntity.IIdentifiable, IUserEntity> staticUserEntityMap = new HashMap<>();

 static Collection<IUserEntity> getUsers(){
   return staticUserEntityMap.values();
 }
}
Community
  • 1
  • 1
Appelemac
  • 192
  • 6
0

you can create abstract SkeletonUserEntity(or AbstractUserEntity) class where you would define this getUser method and all another general methods. All classes have to implemeent IUserEntity you extends from SkeletonUserEntity

Serhii Soboliev
  • 820
  • 1
  • 13
  • 21