简体   繁体   中英

Static methods and interfaces in Java

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 ?

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. eg

Create new method:

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

Call this method from getUsers :

public Collection<IUserEntity>      getUsers() {
  return UserEntity.getUsersStatic();
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM