Let's for fun make an interface:
FooI.java
public interface FooI {
public void doAction();
public boolean doAction2(int value);
public boolean doCompare(FooI foo);
}
Now I'll make two other classes which implements this interface:
Foobar.java
public class Foobar implements FooI{
/**
* Must implement the following methods
* accordingly to the interface
*/
public void doAction() {
// TODO Specify what the action does here
}
public boolean doAction2(int value) {
// TODO Specify what the action does here
return false;
}
public boolean doCompare(FooI foo) {
// TODO Specify what the compare does here
return false;
}
}
Foo.java
public class Foo implements FooI{
/**
* Must implement the following methods
* accordingly to the interface
*/
public void doAction() {
// Do the action here
}
public boolean doAction2(int value) {
// Do the action2 here
if (value > 10) {
return false;
} else {
return true;
}
}
public boolean doCompare(FooI foo) {
return foo.equals(this);
}
/**
* You can add other methods as well.
* You are free to do that
*/
public void doTheFoo() {
System.out.println("Foo!");
}
}
For a small test I've created this little class
Test.java
public class Test {
/**
* Just an example if you want to test it
*/
public static void main(String[] args) {
FooI foo1 = new Foobar();
FooI foo2 = new Foo();
System.out.println(foo1);
System.out.println(foo2);
System.out.println("foo1.doCompare(foo2): " + foo1.doCompare(foo2));
}
}
Since I use FooI foo1 on the left-hand side of the declaration I know that whatever object I set it too it will fulfill the requirements imposed by the interface. Basically have the methods I specified and I can use them if I want to.
I cannot however use methods defined in the class I instantiate if it is not defined in the interface.
I cannot do
foo2.doTheFoo()
If I now did
Foo foo = new Foo() I would be able to do
foo.doTheFoo() just fine.
On a side note: You cannot implement interfaces in interfaces, but you can extend interfaces.