Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Java Interface?
2.1.
Java
3.
Why use Java interface?
4.
How to declare an interface?
5.
History of Java Interface
6.
Features of Java Interface  
7.
Real-Life Example of Interface in Java
8.
Example of Java Interface
8.1.
Java
9.
Relationship Between Class and Interface
10.
Difference Between Interface and Abstract Class
11.
Important Points About Interface in Java
12.
Explain When to use Interface
13.
Nesting Interface 
13.1.
Java
14.
Limitations of Interface in Java
15.
Advantages of Java Interface
16.
Disadvantages of Java Interface
17.
Frequently Asked Questions
17.1.
​​How many Types of interfaces in Java?
17.2.
Why is an interface so important?
17.3.
What is the purpose of an interface?
17.4.
What is interfaces in OOP?
18.
Conclusion
Last Updated: Aug 31, 2024
Medium

Interface in Java

Introduction

Java is one of the most popular and object-oriented programming languages produced by Sun Microsystems. Java provides developers with interfaces for the construction of software systems. Interfaces is named as collection of method declarations. Interface in Java is a collection of constants and abstract methods. Since all methods in an interface are abstract, the abstract modifier is usually left off. An interface can specify what a class must do, but not how it does. Interface fields are public, static, and final by default, and methods are public and abstract. The interface is used to achieve abstraction and multiple inheritance.

Interface in Java

Also see,  Swap Function in Java

What is Java Interface?

An interface in Java is nothing but a class blueprint, and it can have static, constant, and abstract methods. Java uses the interface as a tool to implement multiple inheritances and abstractions. In the interface, there can be only abstract methods, not the method body.

Interfaces provide a way to partition an extensive system into smaller, more manageable chunks. By creating interfaces that reflect particular functionality, it is possible to create smaller, more modular components that may be combined to create a more extensive system. The use of interfaces has the benefit of allowing for more modularity and flexibility in program architecture. It is simpler to swap out various implementations of a set of methods defined in an interface without affecting the rest of the code.

An example of an interface in Java is given below:

  • Java

Java

interface demo { // Declaration of an interface
   void show();
}
class first implements demo { // implementing the interface
   public void show() {
       System.out.println("Hello Ninja! Nice to see you");
   }
   public static void main(String args[]) {
       first obj = new first();
       obj.show(); // calling the interface method
   }
}
You can also try this code with Online Java Compiler
Run Code

Output:

Output

Why use Java interface?

Interfaces are used in Java for the following reasons:

  1. Total Abstraction: Interfaces provide a way to achieve 100% abstraction. They define methods that must be implemented by any class that implements the interface, ensuring a clear contract without any implementation details. 
     
  2. Multiple Inheritance: Java does not support multiple inheritance with classes to avoid complexity and ambiguity. However, interfaces allow a class to implement multiple interfaces, enabling multiple inheritance of method declarations. 
     
  3. Loose Coupling: Interfaces promote loose coupling by allowing classes to interact through the interface rather than specific implementations. This flexibility makes it easier to change or extend the code without affecting other parts of the system.

How to declare an interface?

Syntax to declare an interface:

 interface <interface_name> {
    //constant declarations    
    //declare method signatures that are abstract
}

 

Syntax to implement an interface:

 class <class_name> implements <interface_name> {
   //methods from the interface
}; 

History of Java Interface

Java was developed by Sun Microsystems and was published for usage in 1995.  The interface was given as one of the main characteristics of Java, and initially, it was designed as an abstract type to implement multiple inheritances. Only static constants and abstract methods were the members of the interface definition. In Java 1.1, the knowledge of inner classes was introduced, which meant that a class could be a member of another class.

In the further updations of Java, static nested classes could also be used inside an interface. 

Features of Java Interface  

Some of the significant features of Interface in Java are listed as follows:

Java Interface Features
  • Interfaces can only contain abstract method declarations and cannot include method implementations. Classes can specify a set of methods they will implement using interfaces without revealing the specifics of how they will implement them. This facilitates decoupling and abstraction.
  • Multiple inheritance is not permitted for classes in Java; however, it is possible for an interface. Java classes are not able to derive from multiple classes, although they can implement multiple interfaces. 
  • Interface methods cannot be specified as private or protected because they are public by default. Since interfaces are meant to be used by other classes, all the methods declared in an interface are public by default.
  • Marker interfaces, like Serializable, Cloneable, and Remote, are interfaces with no methods or constants. Marker interfaces are used to identify classes that have particular characteristics or behaviours, such as the capacity to be serialized or cloned. 
  • Constructor methods cannot be included in interfaces. Constructors are not inherited and are used to initialize objects; as a result, they serve no purpose in an interface.
  • Constant declarations, which are by default public, static, and final, can be found in interfaces.

Real-Life Example of Interface in Java

In Java, an interface is a blueprint of a class that defines a set of methods that the class must implement. As an illustration, consider an automobile. Creating an interface called "DrivingInterface" will allow us to specify the methods each car class must include to be considered a "drivable" car. The DrivingInterface, for instance, might have methods for "StartEngine," "accelerate," "brake," and "turn." These methods must be implemented by each automobile class's unique implementation of the DrivingInterface. Java interfaces provide the benefit of allowing for better code organization and abstraction.

In Java, an abstract class is a class that needs to be subclassed by another class to be instantiated. A common interface or behaviour for a collection of related classes is frequently defined using abstract classes. In our example of a car, the abstract class "Car" might describe properties and operations common to all car kinds, such as the number of wheels, the fuel source, and the top speed. 

Example of Java Interface

The given code demonstrates how to implement an interface in Java using an abstract class:

  • Java

Java

// Implementation of Interface using Abstract Class in Java
interface College { // Declaration of the interface
void learnDSA();
void learnWebDevelopment();
void share();
}
// Abstract class Student implementing from College interface
abstract class Student implements College {
// Overriding the methods declared inside the interface
@Override public void learnDSA() {
System.out.println("You must have a good command on DSA to crack good companies");
}
@Override public void learnWebDevelopment() {
System.out.println("Coding Ninjas provides excellent content to master Web Development");
}
}
// Extending the Friends class from Student abstract class
class Friends extends Student {
@Override public void share() {
System.out.println("Helping others to learn will make you learn too!");
}
}
// Driver code
public class Main {
public static void main(String[] args) {
// Creating a new student1 object
Friends student1 = new Friends();
// Calling the methods to get the output
student1.learnDSA();
student1.learnWebDevelopment();
student1.share();
}
}
You can also try this code with Online Java Compiler
Run Code


Output:

Output

 

The provided code specifies an interface for a college with three methods: share(), learnDSA(), and learnWebDevelopment(). After that, an abstract class called Student implements the interface by overriding the two methods, and another class called Friends extends it by implementing the final method. The next step is to define the main() method, which creates an instance of the Friends class and invokes the implemented methods.

Overall, this approach demonstrates how an interface can be partially implemented using an abstract class while still allowing concrete classes to implement the remaining functions independently.

In general, the time complexity of implementing an interface in Java depends on how the interface's methods are implemented specifically and cannot be assessed without looking at the implementation code.

The time and space complexity of the above code implementation is constant, O(1), because each of the methods contains only a single print statement which takes constant time to execute.

Relationship Between Class and Interface

The relationship between a class and an interface in Java is defined by implementation. A class implements an interface, meaning it provides concrete implementations for the abstract methods declared in the interface. This allows the class to commit to the behaviour specified by the interface, ensuring it adheres to a particular contract or protocol, thereby enabling polymorphism and promoting a flexible and modular code structure.

Difference Between Interface and Abstract Class

S.No.InterfaceAbstract
1There can only be abstract methods on an interface.Both abstract and non-abstract methods can be found in abstract classes.
2Constructors are not present in Interface.Constructors are found in abstract classes.
3Interfaces permit multiple inheritance.Abstract classes do not support multiple inheritance.
4It is declared using the interface keyword.It is declared using an abstract keyword.
5In order to implement an interface, the word "implements" is used.In order to implement an abstract class, the word "abstract" is used.
6Interfaces are only capable of extending other interfaces.Abstract classes may implement multiple interfaces and extend other classes.
7The only variables in an interface are static and final.Variables in an abstract class may be final, non-final, static, or non-static.
8Members of the interface are by default public.The members of abstract classes may be private or protected.

Interfaces can be used to achieve abstraction in Java. We can distinguish between the behaviour's specification and implementation by specifying an interface. This implies that rather than relying on their actual implementations, classes can communicate with one another based on their interfaces. As a result, the code becomes more adaptable and readable.

Important Points About Interface in Java

Some of the essential points about Interface in Java are discussed below: 

  • Interfaces cannot be declared with private or protected access specifiers. Only public and default modifiers are allowed. Any combination of public, abstract, or no modifiers is acceptable.
  • Every variable declared in the Interface must be static, public, and final. Any combination of public, static, final, or no modifiers is acceptable.
  • Interface methods cannot be designated as final, strict, or native since they are abstract. When methods are marked as final, they cannot be overridden, and methods without a body are useless.
  • In Java, every interface is, by default, abstract.
  • One or more interfaces may be extended by an interface. It is the only area where more than one class can be extended.
  • The keyword Implements must be used to declare an interface; the abstract keyword is optional and is viewed as unnecessary.
  • In Java, multiple inheritance can be achieved using an interface that allows a class to derive from various interfaces.
  • A nested interface is one that has been declared inside of another interface.
  • Interface variables must be initialized at declaration time. The compiler will throw an error otherwise.

Explain When to use Interface

Interfaces are helpful in a variety of situations, such as;

  • This can be helpful in circumstances where you wish to define a general behaviour that several objects can use.
  • Interfaces are used to allow polymorphism. The capacity of an object to assume various forms is known as polymorphism. You can design a standard set of methods and properties that can be used to communicate with objects of various sorts by utilizing interfaces.
  • Interfaces permit loose connectivity between various system components. You can separate the use of a method or property's implementation from the code that uses it by defining an interface. 
  • A contract for a class or structure can be defined using interfaces. This can be helpful when developing unit tests since it enables you to test a class or structure in isolation without needing to be aware of the specifics of its implementation.

Nesting Interface 

Nested interfaces are interfaces that are specified inside of other interfaces or classes. Nested interfaces are used to group them to make related interfaces easier to maintain. A nested interface must be declared as a static member of the enclosing interface or class. The nested interface can have any access modifier if it is declared within the class, but it must be public if it is declared inside the interface. An example of a nested interface is given below:

  • Java

Java

interface Display{  // Nested Interface declaration
void show();
interface Remark{
void msg();
}
}
class NestedInterface implements Display.Remark{ // Implementing the msg function of inner interface.
public void msg(){System.out.println("Hello Ninja! Happy Coding");}

public static void main(String args[]){
Display.Remark message=new NestedInterface(); //upcasting here
message.msg();
}
}
You can also try this code with Online Java Compiler
Run Code

Output:

output

 

As you can see in the above example, since the Remark interface cannot be accessed directly, we are accessing it through its external interface Display. It is comparable to the room's almirah; we cannot access it immediately without first entering the room. 

Limitations of Interface in Java

Some of the significant limitations of an interface in Java are given below:

  • Interfaces do not contain the implementation code; as a result, classes that implement an interface are required to implement every method defined in the interface.
  • You cannot make an instance of an interface because interfaces lack constructors.
  • You cannot make an instance of an interface because interfaces cannot have constructors.
  • Changing an interface after it has been published might be challenging without disrupting the code that utilizes it. All classes implementing the interface may need to be modified to respond to any changes.

Advantages of Java Interface

Some of the major advantages of an interface in Java are discussed below:

  • Unit testing is made simpler by the interface. If your code uses interfaces for dependencies, you may quickly swap them out for testing with a mock, stub, or dummy. 
  • Java does not permit multiple inheritances, but you can use an interface instead because you can create many interfaces.
  • You can achieve the security of the implementation without worrying about the implementation portion.
  • Java's interface has the advantage of producing loosely coupled code, which is simpler to modify and maintain. You can replace individual components in a loosely coupled code without changing the structure as a whole.
  • Java interfaces offer a method for achieving abstraction by shielding the outside world from a class's implementation specifics. This makes it simpler to modify a class' implementation details without having an impact on the code that utilizes the class.

Disadvantages of Java Interface

Some of the major disadvantages of an interface in Java are discussed below:

  • Once specified, interfaces cannot be altered, which may, in some situations, limit their adaptability.
  • Your code may become more complex and difficult to comprehend if you utilize interfaces to provide another degree of abstraction. 
  • Java interfaces are slower and provide fewer functionalities than other interfaces.
  • Interfaces in Java require more memory space and have no backup facility.

Frequently Asked Questions

​​How many Types of interfaces in Java?

In Java, there are two main types of interfaces: normal interfaces and functional interfaces. Normal interfaces are defined using the interface keyword and contain abstract methods. Functional interfaces, introduced in Java 8, contain exactly one abstract method and can be implemented using lambda expressions, supporting concise and functional programming styles.

Why is an interface so important?

Interfaces are crucial for software development because they support modularity and reuse. Different software components can be created and tested independently by specifying a set of interfaces, which makes the system simpler to maintain and update over time.

What is the purpose of an interface?

An interface represents an assurance of methods that a class must implement. It ensures consistency and enables polymorphism, allowing different classes to be used interchangeably based on shared behaviors.

What is interfaces in OOP?

In Object-Oriented Programming (OOP), interfaces define a blueprint of methods. They establish an agreement, promoting code consistency and enabling polymorphism by allowing convertible implementations.

Conclusion

In this blog, we have learned that an interface is a blueprint of a class, and it can have static, constant, and abstract methods. We have seen what is an interface in Java, its history, features, implementation, advantages and disadvantages, its differences with abstract classes, along with some frequently asked questions related to it.

For more information, refer to our Guided Path to upskill yourself in PythonData Structures and Algorithms, Competitive ProgrammingSystem Design, and many more! 

Head over to our practice platform, Code360, to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more! 

Happy Learning!!

Live masterclass