Skip to content

Instantly share code, notes, and snippets.

@tomlins
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomlins/c9daaeccd8d826de699f to your computer and use it in GitHub Desktop.
Save tomlins/c9daaeccd8d826de699f to your computer and use it in GitHub Desktop.
The following code examples demonstrate where and how to use nested classes in your interfaces. It may look a bit strange at first, an interface with a nested class but after following the examples below it should make sense and you'll see how it fits together. The main thing to come away with is that the interface strictly types the classes tha…
import java.util.*;
public interface Input {
public class KeyEvent {
public static final int KEY_DOWN = 0;
public static final int KEY_UP = 1;
public int type;
public int keyCode;
public char keyChar;
}
public void keyPressed(KeyEvent keyCode);
public List<KeyEvent> getKeyEvents();
}
import java.util.*;
class KeyboardInput implements Input {
private ArrayList<KeyEvent> keyEvents = new ArrayList<>();
public void keyPressed(KeyEvent keyEvent) {
keyEvents.add(keyEvent);
}
public List<KeyEvent> getKeyEvents() {
return keyEvents;
}
}
class KeyboardTest {
public static void main(String... args) {
Input input = new KeyboardInput();
// This works, our KeyEvent is of type Input
Input.KeyEvent keyEvent = new Input.KeyEvent();
keyEvent.keyCode = 65;
input.keyPressed(keyEvent);
// or this...still of type Input
KeyboardInput.KeyEvent keyEvent2 = new KeyboardInput.KeyEvent();
keyEvent2.keyCode = 96;
input.keyPressed(keyEvent2);
// output the events...
for (KeyboardInput.KeyEvent theKeyEvent : input.getKeyEvents()) {
System.out.println("KeyEvent.keyCode : " + theKeyEvent.keyCode);
}
// This following fails to compile as this KeyEvent is not of type Input
// Comment out to compile this class.
KeyEvent myKeyEvent = new KeyEvent();
myKeyEvent.keyCode = 96;
input.keyPressed(myKeyEvent);
}
}
public class KeyEvent {
public static final int KEY_DOWN = 0;
public static final int KEY_UP = 1;
public int type;
public int keyCode;
public char keyChar;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment