Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created June 18, 2010 17:17
Show Gist options
  • Save JoshCheek/443918 to your computer and use it in GitHub Desktop.
Save JoshCheek/443918 to your computer and use it in GitHub Desktop.
Example of how to use a Java interface as a type
// note that all the static keywords on the methods and interface are just b/c I'm implementing these as belonging to the Dialer class
// rather than as belonging to an instance of Dialer
// if you aren't nesting them like this (which you prbably aren't) then you won't need to do that
public class Dialer {
public abstract static interface Dialable { public abstract String dial(); }
public static class Phone implements Dialable {
private String number;
public Phone(String number) { this.number = number; }
public String dial() { return "Now dialing " + number; }
}
// apparently there is some retarted bullshit where inner classes can't have static vars
public static class Clock implements Dialable {
private int face;
public Clock(int face) { this.face = face; }
public String dial() {
return "This clock has a " + new String[]{ "Sun" , "Twelve Hour" ,"Twenty Four Hour" }[face] + " Dial";
}
}
// ===== THE Dialer CLASS ITSELF =====
public static void main(String[] args) {
Dialable[] dialables = new Dialable[]{ new Phone("123-456") , new Clock(0) , new Clock(1) , new Phone("938-9582") , new Clock(2) };
new Dialer(dialables).printDialables();
}
private Dialable[] dialables;
public Dialer(Dialable[] dialables) { this.dialables = dialables; }
public void printDialables() {
for( Dialable dialable : dialables ) System.out.println( dialable.dial() );
}
}
@hemantuno
Copy link

Great

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