Skip to content

Instantly share code, notes, and snippets.

@zlargon
Last active December 14, 2016 07:21
Show Gist options
  • Save zlargon/c9afa1c4f5c601b6952f5ed569324e04 to your computer and use it in GitHub Desktop.
Save zlargon/c9afa1c4f5c601b6952f5ed569324e04 to your computer and use it in GitHub Desktop.
An Example of Java Interface
public class CloudService {
// LoginCallback interface
static public interface LoginCallback {
public void onSuccess(final String loginId, final String token);
public void onFailure(final String loginId, final int errorCode);
}
// login method
static public void login(
final String id,
final String password,
final LoginCallback loginCallback) {
if (id == null || password == null) {
loginCallback.onFailure(id, -1); // TypeError = -1
return;
}
// Query from cloud server
if (id.equals("zlargon") && password.equals("123")) {
loginCallback.onSuccess(id, "token:zlargon:123");
return;
}
// Http Timeout = -2
// Wrong Username/password = -3
loginCallback.onFailure(id, -3);
}
}
public class Example {
public static void main(String [] args) {
CloudService.login("zlargon", "123", new CloudService.LoginCallback() {
@Override
public void onSuccess(final String loginId, final String token) {
System.out.println("Login success: token = " + token);
};
@Override
public void onFailure(String loginId, int errorCode) {
System.out.println("Login failure: error code = " + errorCode);
};
});
}
}
public class Example2 {
public static void main(String [] args) {
MyCallback myCallback = new MyCallback();
CloudService.login("zlargon", "000", myCallback);
}
}
class MyCallback implements CloudService.LoginCallback {
@Override
public void onSuccess(final String loginId, final String token) {
System.out.println("Login success: token = " + token);
};
@Override
public void onFailure(String loginId, int errorCode) {
System.out.println("Login failure: error code = " + errorCode);
};
}
@zlargon
Copy link
Author

zlargon commented Dec 10, 2016

How to build

$ rm *.class
$ javac *.java

Run Example

$ java Example
$ java Example2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment