'Coding has over 700 languages', '67% of programming jobs aren’t in the technology industry', 'Coding is behind almost everything that is powered by electricity'
Last Updated: Dec 19, 2023

Interface in Java

gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

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. A Java interface 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

This blog will briefly give a better understanding of the interface in Java along with its implementation.

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
   }
}

Output:

Output
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Need of Interface in Java

Interfaces are necessary in Java for several reasons:

Need of Interface in Java
  • It is used to achieve data abstraction in Java.
     
  • Java does not allow multiple inheritances for classes, but an interface can accomplish multiple inheritances.
     
  • It provides a method for breaking down a complicated system into more manageable pieces.
     
  • It is applied to produce loose coupling, which makes the classes independent of one another.

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. 

Java Interface Features 

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 behaviors, 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.

Java Interface Example in Real-Life

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 being 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 behavior 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. 

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 behavior'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, strictfp, 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.

Interface syntax

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
}; 

Java Interface Implementation Example

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();
}
}


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.

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 behavior 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 struct can be defined using interfaces. This can be helpful when developing unit tests since it enables you to test a class or struct 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();
}
}


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

What is Java Interface?

In Java, a class's blueprint is known as an interface. It includes static constants and abstract methods. Java uses the interface as a method to achieve abstraction and multiple inheritance. The Java interface can only have abstract methods; method bodies are prohibited.

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 on Coding Ninjas Studio to upskill yourself in PythonData Structures and Algorithms, Competitive ProgrammingSystem Design, and many more! 

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

Happy Learning!!

Previous article
Character Class in Java
Next article
Byte Class in Java
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass