Defining an interface in java
In java, an interface is similar to a class, but it contains abstract methods and static final variables only. The interface in Java is another mechanism to achieve abstraction.
We may think of an interface as a completely abstract class. None of the methods in the interface has an implementation, and all the variables in the interface are constants.
All the methods of an interface, implemented by the class that implements it.
The interface in java enables java to support multiple-inheritance. An interface may extend only one interface, but a class may implement any number of interfaces.
🔔 An interface is a container of abstract methods and static final variables.
🔔 An interface, implemented by a class. (class implements interface).
🔔 An interface may extend another interface. (Interface extends Interface).
🔔 An interface never implements another interface, or class.
🔔 A class may implement any number of interfaces.
🔔 We can not instantiate an interface.
🔔 Specifying the keyword abstract for interface methods is optional, it automatically added.
🔔 All the members of an interface are public by default.
Defining an interface in java
Defining an interface is similar to that of a class. We use the keyword interface to define an interface. All the members of an interface are public by default. The following is the syntax for defining an interface.
interface InterfaceName{
...
members declaration;
...
}
Let's look at an example code to define an interface.
interface HumanInterfaceExample {
void learn(String str);
void work();
int duration = 10;
}
In the above code defines an interface HumanInterfaceExample that contains two abstract methods learn(), work() and one constant duration.
Every interface in Java is auto-completed by the compiler. For example, in the above example code, no member is defined as public, but all are public automatically.
The above code automatically converted as follows.
interface HumanInterfaceExample {
public abstract void learn(String str);
public abstract void work();
public static final int duration = 10;
}
In the next tutorial, we will learn how a class implements an interface to make use of the interface concept.