“Interface” is used to implement abstraction, multiple inheritance, and polymorphism in Java. It helps in separating a part of code from its implementation. This resultantly assists in updating the code effectively keeping the other code intact. Moreover, this functionality helps programmers split complex codes into the same or different files. This improves the readability of code and enhances the invoke process.
What is an Interface in Java?
An interface is an abstract type used to represent the class behavior. It is declared using the “interface” keyword. It can contain “static” as well as “abstract” methods.
Declaration Syntax
interface x {
// declare methods
}
Here, “x” is the interface name. It is implemented in the target class using the “implements” keyword.
What are the Types of Interfaces in Java?
There are two types of interfaces in Java:
- Marker Interface.
- Functional Interface.
The “Marker Interface” is an empty interface having no method i.e., Serializable, etc. The “Functional Interface”, however, comprises only one abstract method and can contain a flexible number of static and abstract methods as well.
What are Interfaces in OOP?
In OOP, the interface signifies a data type used for class abstraction. These interfaces are used to specify which methods need to be applied by a specific class in inheritance.
Important Considerations
- The abstract methods specified in the interface do not have a body.
- The “static” and “private” methods in the interface can have a method body that defines the method.
- The “private” methods cannot be invoked from outside the interfaces since these are invisible.
- Multiple inheritance is supported in interfaces.
- The interface methods are assigned as “public” and “abstract” by default. The interface fields, however, are “final”, “static” and “public”.
- A class can apply/implement multiple interfaces.
- Constructors are not supported in interfaces.
- The “main” method is not allowed in interfaces.
Example 1: Implementing an Interface in Java
The following code example implements an interface containing an abstract/public method:
package jbArticles;
interface Template{
public void displayName();
}
class Sample implements Template{
public void displayName() {
System.out.println("The name is Lisa");
}
}
public class Interfaceimplement{
public static void main(String[] args){
Sample x = new Sample();
x.displayName();
}}
Code Explanation
- Declare an interface named “Template” containing the specified abstract method.
- Define the class “Sample” that implements the interface via “implements”.
- In the class definition, the method “displayName()” prints the given message.
- In “main”, create a class instance and invoke the method.
Output
Note that the interface can also be defined in a completely different file(of the interface type), as follows:
In this specific implementation, executing either of the files returns the same output i.e., the method’s implementation.
Example 2: Using an Interface With “static” and “private” Methods in Java
In this example, the “main” method invokes the implemented “static” and “private” methods from the interface. This implies that there is no need for the class to implement the interface in this case:
package jbArticles;
interface Sample{
static void displayName() {
System.out.println("The name is Lisa");
}
private void displayAge() {
System.out.println("The age is 23");
}
}
public class Interfaceimplement {
public static void main(String[] args){
Sample.displayName();
}}
Code Explanation
- Define the interface “Sample” containing both the “static” and “private” methods with the body, respectively.
- In main, invoke the “static” method using the interface name.
Output
Since the “private” method is not visible from outside the class. Therefore, invoking the “private” method from the interface in “main” returns an error:
Example 3: Real-Life Scenario of Implementing Interface Using “Overloading” and “Overriding”
The below code example implements the interface containing the parameterized abstract methods. Moreover, these methods are overridden and overloaded for the required implementation:
package jbArticles;
interface Sample{
abstract void displayName(String name);
abstract void displayAge(int age);
}
class Parent implements Sample{
public void displayName(String name) {
System.out.println(name);
}
public void displayAge(int age) {
System.out.println(age);
}
public void displayAge(int age1, int age2) {
System.out.println(age1);
System.out.println(age2);
}
}
class Subclass extends Parent {
public void displayName(String name) {
System.out.println(name);
}
public void displayAge(int age) {
System.out.println(age);
}
}
public class Interfaceimplement {
public static void main(String[] args){
Parent x = new Parent();
Subclass y = new Subclass();
System.out.println("Parent Class Implementation");
x.displayName("Harry");
x.displayAge(18);
x.displayAge(21,22);
System.out.println("\nChild Class Implementation");
y.displayName("David");
y.displayAge(50);
}}
Code Explanation
- Likewise, define the interface containing the given abstract methods.
- Declare the parent class “Parent” that implements the interface.
- In the class body, declare the methods and print the given messages based on the passed arguments.
- Note that in this class, the “displayAge()” method is overloaded with two arguments.
- Now, declare the child class “Subclass” that inherits the superclass’s implementation.
- Override the methods defined in its parent class.
- In “main”, create the instances of both the parent and child classes.
- Invoke the parent class method along with the overloaded “displayAge()” method.
- Likewise, access the child class overridden methods.
Output
How to Implement Multiple Interfaces in Java?
Here, multiple interfaces are implemented by associating the “implements” keyword with multiple interfaces to implement:
package jbArticles;
interface x{
abstract void displayName(String name);
}
interface y{
abstract void displayAge(int age);
}
class Sample implements x, y{
public void displayName(String name) {
System.out.println(name);
}
public void displayAge(int age) {
System.out.println(age);
}
}
public class Interfaceimplement {
public static void main(String[] args){
Sample x = new Sample();
x.displayName("Harry");
x.displayAge(18);
}}
Code Explanation
- Declare two interfaces each having the specified parameterized abstract method.
- Define the class “Sample” that implements both interfaces at the same time.
- In the class definition, define the specified methods.
- In “main”, create a class object and invoke the class methods.
Output
How to Perform Multiple Inheritance in Java Using Interface?
Although multiple inheritance is not supported in Java, the interfaces can be used to implement multiple inheritance.
Following is the graphical representation:
Below is the code example implementing multiple inheritances:
package jbArticles;
interface x {
default void displayName(String name) {
System.out.println(name);
}
}
interface y extends x {
abstract void displayAge(int age);
}
interface z extends y {
}
class Sample implements z{
public void displayAge(int age) {
System.out.println(age);
}
}
public class Interfaceimplement {
public static void main(String[] args){
Sample x = new Sample();
x.displayName("Harry");
x.displayAge(18);
}}
Code Explanation
- Declare the interface “x” that includes a “default” method printing the passed value.
- Define another interface “y” that inherits from the “x” interface. This specific interface contains the given abstract method.
- Create another interface that inherits from the “y” interface having an empty body.
- Specify the class that implements the “z” marked interface that is inherited from both the above interfaces.
- Note: The marked interface is the one that does not have any method and is specified as a marker only.
- In this class, declare the “displayAge()” method that returns the age passed as its argument.
- In “main”, create an instance of the “Sample” class and invoke the default method from the “x” interface via multiple inheritances and the class method, respectively.
Output
How to Implement a Nested Interface in Java?
A nested interface is not implemented directly. Instead, it must be associated with the outer interface when invoked, as specified below:
package jbArticles;
interface x {
void input();
interface y {
void display();
}}
public class Interfaceimplement implements x.y{
public void display() {
System.out.println("The name is David");
}
public static void main(String[] args){
x.y ob = new Interfaceimplement();
ob.display();
}}
Code Explanation
- Create an interface named “x” containing the given method.
- Within this interface, declare another nested interface “y” having the stated method.
- Implement the nested interface in the public class by referring to the outer class using “implements”.
- In this class, include the definition of the nested interface method.
- In “main”, create an instance of the class by referring to the nested interface.
- Access the class method to return the method implementation.
Output
How to Implement a Marker Interface in Java?
A marker interface does not have any methods or implementation. The below code uses the “Serializable” marker interface that is implemented without applying any of its methods:
package jbArticles;
import java.io.Serializable;
public class Interfaceimplement implements Serializable {
public int id = 2;
public String age = "23";
public String city = "Los Angeles";
}
In this code, the “Serializable” interface is implemented via the “Interfaceimplement” class directly. Also, it is verified that it does not contain any method to implement from the interface.
How to Invoke Variables From an Interface in Java?
The below section includes the code to access and display the variables from an interface:
package jbArticles;
interface x {
int x = 5; boolean w = true;
static int y = 10;
final double z = 20.456;
String p = "Wick";
}
public class Interfaceimplement implements x{
public static void main(String[] args){
System.out.println(x);
System.out.println(w);
System.out.println(y);
System.out.println(z);
System.out.println(p);
}}
Code Explanation
- Define the interface named “x” having the given variables initialized to the corresponding values.
- Specify the class “Interfaceimplement” that implements the “x” interface.
- In “main”, invoke the variables directly.
Output
Relationship Between Classes and Interfaces in Java
Advantages of Interfaces
- These implement abstraction.
- The interfaces can apply multiple inheritance, unlike classes.
- Multiple interfaces can be implemented effectively.
- Loose coupling can be done using interfaces.
Note: The downside of interfaces is that these are hardly utilized in real-world projects. Also, they can affect the speed of code execution.
Why Use Interfaces Instead of Abstract Classes?
Both functionalities perform almost in the same way. However, interfaces are used to flexibly apply the same/common functionality to unrelated cases. Also, the abstract classes can have non-final variables whereas interface variables are public, static, and final.
Differences Between Interface and Class
Interface | Class |
---|---|
It supports multiple inheritance. | It does not support multiple inheritance. |
It’s instance cannot be created. | It can be instantiated. |
The interface can only be of “public” type. | The class can be “public”, “private”, “final” or “protected” etc. |
Conclusion
An interface in Java is an abstract type for specifying the class behavior. It is declared using the “interface” keyword and helps in abstraction. In programming, usually the “functional” interface is used to implement different functionalities. Also, an interface is recommended when there is a requirement to split the code, thereby making it readable and placing the alike functionalities in one place.