C. Adkin C. Adkin - 1 month ago 5
Java Question

In the implementation of my interface A I want to return an instance of type interface B

I've been trying to work this out for a couple of days now and I need a little push in the right direction.

The issue:

I'm trying to build a simple log-in system in my web-application. I'm trying to make it so that there's loose coupling between my classes.
I built two interfaces;

public interface Authenticable {
String getUsername();
boolean changePassword(char[] password);
}


This interface will be implemented by classes that can be authenticated.




public interface Authenticator {
Authenticable authenticate(String username, char[] password) throws AuthenticationException;
}


And this interface will be implemented by classes that can authenticate an Authenticable.




Currently I do not have a database or anything but I decided I want to be able to build a simple Authenticator first and later be able to swap it out for a different one (Which might use a database or a filesystem).

So the first implementation I made was:

public class HardcodedAuthenticator implements Authenticator {
@Override
public Authenticable authenticate(String username, char[] password) throws AuthenticationException {
if (username == "test" && password == new char[]{'t', 'e', 's', 't'}) {

}
}
}


This implementation simply checks if the username equals 'test' and the password equals 'test'.

If it does: Return an instance of Authenticable.

If it doesn't: Throw an AuthenticationException.




However in my HardcodedAuthenticator I don't want to be limited to an implementation of the Authenticable (Atleast that's what I think would be best) but I still want to be able to return an instance of Authenticable..

The question:

How does implementation Y of interface A return an instance of interface B?

Thanks a lot in advance.

Christian Adkin

Answer

if I understand your problem correctly You dont want your implementation of Authenticator to have a dependency on any specific implementation of Authenticable you need to inject reference of type Authenticable to your Authenticator

        public interface Authenticator {
                  Authenticable authenticate(String username, char[] password,Authenticable authenticable) throws AuthenticationException;
       }

try to do some research about dependency injection, you will find many helpful articles if you still confused about it.