Java interface contract
Suppose you have an interface defined like this:
interface someInterface {
Object someMethod(Object someObject);
}
First thing you have to know is that interfaces are only public if you define them as such. If you don’t they can only be implemented by classes in that package.
Just like the interfaces themselves, the methods defined in an interface are public no matter if you define them as so. Please also note that you cannot define interface members (methods or variables) as private. All you can do is have them public and/or abstract. Just as a quick reminder, a constant in Java is defined as public static abstract.
By looking at the signature of the method someMethod, it is clear that it requires an Object (someObject) and that it returns a result – an object. This is the contract defined by the interface.
Java is a complex language – defining the method as returning an object allows you to return whatever type of an object you want. You can return a String, a Collection (for instance a List) and, starting from Java 5, even a primitive like int because out of the box that primitive will be wrapped inside an Integer object and unwrapped after the call.
One thing you have to be careful when defining a class that implements this method is that you might be tempted to define it like this:
String someMethod(Integer someInteger).
After all someMethod expects an Object and Integer is an Object, right? Well, in Java all classes extend the Object class, so that should make sense. BUT that would brake the contract. The programmer looking at the interface contract would expect to be able to call someMethod with any object. If you were able to define someMethod expecting an Integer, that method could not possibly accept an Object because Object is not necessarely an Integer! So the answer is NO – when you implement someMethod, you have to follow the signature from the interface, as far as the arguments go. Although YOU CAN call the method with any kind of objects you want, since it just expects an object.
Remember, you can implement the interface by making it return the type of object specified in the signature or objects that extend it, but you have to keep the same objects in the arguments.




