An interface is basically just a class without any data, and without implementations for any of its methods.
To implement the interface, a class
must have methods with the same name as the methods in the interface.
It's just a way to treat lots of objects in the same way.
The canonical example is a "Drawable" interface. Things which implement Drawable must have a draw method.
Code:
interface Drawable {
void draw();
}
So you could have a circle and a square class, and then put them into an array of drawables.
Code:
interface Drawable {
void draw();
}
class Circle implements Drawable {
float x,y,d;
Circle(float x, float y, float d) {
this.x = x;
this.y = y;
this.d = d;
}
void draw() {
ellipseMode(CENTER);
ellipse(x,y,d,d);
}
}
class Square implements Drawable {
float x,y,w;
Square(float x, float y, float w) {
this.x = x;
this.y = y;
this.w = w;
}
void draw() {
rectMode(CENTER);
rect(x,y,w,w);
}
}
Drawable[] thingsToDraw;
void setup() {
size(300,300);
smooth();
thingsToDraw = new Drawable[10];
thingsToDraw[0] = new Circle(random(width),random(height),10);
thingsToDraw[1] = new Circle(random(width),random(height),20);
thingsToDraw[2] = new Circle(random(width),random(height),30);
thingsToDraw[3] = new Circle(random(width),random(height),40);
thingsToDraw[4] = new Circle(random(width),random(height),50);
thingsToDraw[5] = new Square(random(width),random(height),10);
thingsToDraw[6] = new Square(random(width),random(height),20);
thingsToDraw[7] = new Square(random(width),random(height),30);
thingsToDraw[8] = new Square(random(width),random(height),40);
thingsToDraw[9] = new Square(random(width),random(height),50);
noLoop();
}
void draw() {
background(0);
stroke(255);
strokeWeight(2.0);
fill(255,0,0,100);
for (int i = 0; i < thingsToDraw.length; i++) {
thingsToDraw[i].draw();
}
}
Note that you could do this without the interface. Instead, you would have a common base class for Drawable, with an empty draw method. The Circle and Square would say extends Drawable instead, and they would implement draw in the same way.
Code:
class Drawable {
void draw() {
// do nothing
}
}
class Circle extends Drawable {
void draw() {
// do something...
}
}
Once you understand the difference between implementing interfaces and extending classes you might want to look up abstract classes, which are halfway between the two.