When is an interface used?
A class that implement interface must implement all the methods declared in the interface.
To implement interface use implements keyword. Since java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance . It is also used to achieve loose coupling.
Also, consider a below Java example where I have a program that displays pages of data on the screen. Initially I want it to get the data from a database or XML files. If I write my program so that it uses interfaces I can define an interface like so:
public interface PageDatasourceInterface {
public List getPages();
}
And use it like so:
PageDatasourceInterface datasource123 = // insert concrete PageDatasourceInterface implementation here
List pages1 = datasource123.getPages();
display(pages1);
And we can then write separate database and XML implementations that adhere to this interface:
public class DatabasePageDatasource implements PageDatasourceInterface {
public List getPages() {
// Database specific code
}
}
public class XmlPageDatasource implements PageDatasourceInterface {
public List getPages() {
// XML specific code
}
}
Recent Comments