What is an Interface? @ oracle.com[
^]
to complete that: it's a representation of an object.
So for example:
You want to provide the possibility of making input to your system - you could grant complete access:
public class MyObject(){
public myobject(){
}
public SecretData returnSecret(){
return oSecretData;
}
}
But that's not the best idea. You better create an interface just representing the functions the other side needs:
public Interface IMyObject(){
public OfficalValue getOfficalValue();
}
public class MyObject() implements IMyObject{
IMyValue oMyValue;
public myobject(){
oMyValue = this;
}
public IMyObject grantAccess(){
return oMyValue;
}
private SecretData returnSecret(){
return oSecretData;
}
@Override
public OfficalValue getOfficalValue(){
return oOfficalValue;
}
}
An interface can also be a common base for a variation of objects. The interface, which all objects are implementing is the guarantee to have the same access to all of the objects.
In this example all Vehicles are able to park and drive - only the tractor is able to pull a trailer:
public class RoadTraffic{
public void moveVehicles(Object oParticipatingObject){
if(oParticipatingObject instanceof IVehicle){
IVehicle oVehicle = (IVehicle) oParticipatingObject;
oVehicle.drive();
if(oVehicle instanceof Tractor){
((Tractor)oVehicle).pullTrailer();
}
}
}
}
public Interface IVehicle{
public void park();
public void drive();
}
public class Car implements IVehicle{
public void park(){ }
public void drive(){ }
}
public class Tractor implements IVehicle{
public void park(){ }
public void drive(){ }
public void pullTrailer(){
}
}
Other good uses are to store static values in there - like ID's and common used values that are used in different objects:
public interface IConstants{
public static final String
GEAR = "",
LIGHT = "",
...
}
public class MyObject{
public void drive(){
if(IConstants.LIGHT.equals(...){
}
}
}
I hope I didn't miss to much and didn't write to much fails in here.