Page Stats
Visitor: 305
Java Interface
An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with a major difference. The difference is that interface defines only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields contain only constant values.
Therefore, it is the responsibility of the class that implements an interface to define the code for these methods.
Syntax to declare interface.
interface <interface name> { [fields declaration]; [method declaration]; }
Difference between Interface and Abstract Class
- An interface cannot implement any methods, whereas an abstract class can.
- A class can implement many interfaces but can have only one super class.
Why we use interface then?
Let's say I want you to make an application that should have one method. Method that takes two integer data type parameters and performs some operation on them, returning value is void.
So, you should use a method with two integer parameters and whatever the code is required to perform that operation in that method. It is the way of standardizing the software engineering process where designers give you interfaces and coders write the code. You cannot choose naming convention that suits you, interface is a contract that you must follow.