What is Interface
In this tutorial, we are going to discuss what is interface in java. An interface is a completely “abstract class” that is used to group related methods with empty bodies.
- Any service requirement specification (SRS) is considered as Interface.
- From the client point of view, an interface defines the set of services that they are expecting.
- From the service provider point of view, an interface defines the set of services that they are offered.
- Hence an interface is considered as a contract between client and service provider.
E.g
- By using the bank ATM GUI screen, bank people will highlight the set of services that they are offering at the same time the same screen describes the set of services that the end-user is expected. Hence this GUI screen acts as the contract between bank people and customers.
- Within the interface, we can’t write any implementation because it has to highlight just the set of services what we are offering or what you are expecting. Hence every method present inside the interface should be abstract. Due to this, the interface is considered as 100 % pure abstract class.
Advantages
The main advantage of interface are
- We can achieve security because we are not highlighting our internal implementation.
- The enhancement will become very easy because we can change our internal implementation without affecting the outside person.
- Two different systems can communicate via an interface (A java application can talk with a mainframe system through an interface)
Declaration and implementation of an interface
- We can declare an interface by using the interface keyword. We can implement an interface using implements keyword.
interface Interf {
void m1(); // by default public abstract void m1();
void m2();
}
abstract class ServiceProvider implements Interf {
public void m1() {
---------
---------
}
}
- If a class implements an interface compulsory, we should implement every method of that interface. Otherwise, we have to declare a class as abstract. Otherwise, it leads to a compile-time error.
- Whenever we implement an interface method compulsory, it should be declared as public. Otherwise, we will get a compile-time error.
extends vs implements
- A class can extend only one class at a time.
- A class can implement any number of interfaces at a time.
- A class can extend a class and can implement any number of interfaces simultaneously.
- An interface can extend any number of interfaces at a time.
interface A {
}
interface B {
}
interface extends A,B {
}
That’s all about what is interface in java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!
What is Interface