1

I have an class with a static interface within it.

public class UserInfo {

   private Store userInfoStore;

   public static interface Store {
       UserInfo save(UserInfo userInfo);
   }
   public UserInfo save() {
       if (userInfoStore == null) return null;
       return userInfoStore.save(this);
   }

}

I then have an object which implements the above object's interface

public class UserAuditService implements UserInfo.Store {
    @Override
    public UserInfo save(UserInfo userInfo) {
        // code that persists object to disk
    }
}

Now say I'm creating an instance of the UserInfo object somewhere else in my application. How do I reference the save method implemented in the UserAuditService class?

UserInfo userInfo = new UserInfo();
??? - Not sure what to do here.
3
  • I suppose that's subjective. I've removed the term. Commented Mar 17, 2015 at 11:43
  • what do you want to do at ??? Commented Mar 17, 2015 at 11:44
  • you have created an object of UserInfo now what next you want to do? Commented Mar 17, 2015 at 11:46

2 Answers 2

2

If save method is what you want to call then do the following:

UserInfo userInfo = new UserInfo();
UserInfo.Store userStore = new UserAuditService();
userStore.save(userInfo);

This is one way of using the implemented method.

Sign up to request clarification or add additional context in comments.

1 Comment

Is there cases when you will use private Store userInfoStore;? in the @Falak example, this field in not used.
1

You mean you don't want to hardcode the UserAuditService class, because there may be many implementations in the future?

There are many solutions, it's what the dependency injection is all about.

You may use Spring or other dependency injection framework, and configure the class to use in xml (or by annotations).

You may do it by hand, for example using constructor dependency injection (you add field of type UserInfo.Store to the UserInfo class, and assign to it a class passed as parameterin a constructor of UserInfo).

Another option is setter dependency injection - you have the same field in UserInfo, but you set it in a setter called from some place after the UserInfo was created.

This makes it clear what happens, but requires to pass the dependencies all the way from the place you configured it to the place they are used, that's why people use dependency injection frameworks to cut the boilerplate.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.