You could use a structure where you have a superclass and a child class that extends that superclass and inherits the parent functions. An interface here isn’t the best choice.
Interfaces are particularly useful if your code involves a common type which has many implementations. The best example here would be the Java Collections API. There is an interface called [icode]List[/icode] and there are a lot of implementations of it like [icode]ArrayList[/icode], [icode]LinkedList[/icode] etc.,
As @opiop65 pointed out, interfaces are not the best option here. You could instead go with a superclass with subclasses since you are only seeking method overloading.
It’s not been about your answer. It was a (inserious) suggestion to the original poster. Smalltalk programmers won’t think it’s obscure though, since in smalltalk you just need the method name and no interface or super class.
Google is your friend. This is a very basic and very broad question. I’ll give you some basics about it though.
An interface is pretty much a partial template for the class. It forces a class that “implements” an interface to have all the functions that the interface states and forces you to define what they do.
If you know what an abstract/virtual method is. A interface is a class that is made up of only abstract/virtual methods.
for example, you mentioned the runnable interface. The whole interface simply looks like this.
public interface Runnable
{
public void run();
}
so anything that implements Runnable must have the run() function, but every class defines the run function themselves. This guarantees that any Runnable object has the method run().
Ill give you a simple example.
public interface Drawable
{
public void draw();
}
Example class that uses drawable:
public class Car implements Drawable
{
//other car methods
public void draw()
{
//explain how to draw a car
}
}
public class Game
{
Drawable[] drawThese;
public Game()
{
drawThese = new Drawable[2];
drawThese[0] = new Car(); //polymorphism
drawThese[1] = new otherDrawableThing();
}
public void gameLoop()
{
//do other game loop stuff here
for(int i = 0; i < drawThese.length; i++)
drawThese[i].draw(); //all drawable objects have this method tho they
//define them differently
}
}
edit: there is a lot more to learn. Google. Also note the useful characteristic that you can implement as many interfaces as you want and you can only extend from one class in Java.
The reason interfaces exist is for cross-cuts. Draw a picture of a tree. That represent a class hierarchy. Now if you need common functionality down the tree in nodes whose common parent are far toward the root then you need an interface to make them type compatible for that functionality. Or similarly to make type compatible classes that creating a common base class is impossible/impractical because they are out of your control.