Reputation: 3040
I have a question about overloading in Java. I have these functions in a class:
public class DefaultMmfgCustomerFacade extends DefaultCustomerFacade {
private MmfgUserService mmfgUserService;
private MmfgSessionService mmfgSessionService;
private UserProfileConfigurator userProfileConfigurator;
@Override
public void forgottenPassword(final String email) {
Assert.hasText(email, "The field [email] cannot be empty");
final CustomerModel customerModel = (CustomerModel) getMmfgUserService().getUserForEmail(email.toLowerCase(),
null);
// getUserService().getUserForUID(uid.toLowerCase(), CustomerModel.class);
getCustomerAccountService().forgottenPassword(customerModel);
}
public void forgottenPassword(final String email, final String uid) {
Assert.hasText(email, "The field [email] cannot be empty");
Assert.hasText(uid, "The field [uid] cannot be empty");
final CustomerModel customerModel = (CustomerModel) getMmfgUserService().getUserForEmail(email, uid);
// getUserService().getUserForUID(uid.toLowerCase(), CustomerModel.class);
getCustomerAccountService().forgottenPassword(customerModel);
}
}
I would call the forgottenPassword(String, String) function in another class in this way:
getCustomerFacade().forgottenPassword(form.getEmail(), form.getUid());
but I obtain an error at compilation time.
The forgottenPassword(String) function is an @Override. The second function instead is an overload. How I have to call the second function?
Thank you all, but I didn't ever use overloading in Java.
Upvotes: 0
Views: 314
Reputation: 337
In java if you have two methods with same names but different arguments lists, they are really two different methods. Like if you had two methods with different names. It makes no difference for the compiler. The arguments lists differ => these are two different methods.
In your case you have a base class/interface DefaultCustomerFacade with one method declared in it. You have an implementation DefaultMmfgCustomerFacade that overrides that declared method. When you overload that method in DefaultMmfgCustomerFacade, it will behave the same way as if you added any other method with different name. There's no way for compiler to know that the method is overloaded in the implementation of DefaultCustomerFacade.
So you have two choices:
The first one is more preferable of course, because you will be able to change the implementation without modifying/recompiling client code. And it's generally a good rule to use interfaces instead of concrete implementations where possible. This will make your code less coupled and easier to maintain.
Upvotes: 2
Reputation: 31
The problem is that forgottenPassword(String) is a function in DefaultCustomerFacade that you are overriding. To override, you need to match the function signature exactly.
I would suggest choosing a different name for both functions, and have the overriding function call the other one.
eg:
Upvotes: 0