Ever questioned how to use an interface in Java? The interface is the pinnacle of Java's Object-Oriented Programming. Code readability and project speed are enormously improved, and a completely new level of data abstraction is achieved. The Java Programming Language's Java Interface is an advanced level of abstraction. Java interface makes things easier to read and less complicated, which reduces code complexity.
Computer interface is referred to be a line dividing two or more systems. It transfers information—which could be signals, commands, or protocols—between system components.
Java Abstraction offers a method's functionality by concealing the implementation logic contained within the method. In a similar vein, the Java Interface is also an Abstract Class that only contains the method declaration. An interface is implemented by a class in order to inherit abstract methods. An interface may also have constants, static methods, nested interfaces, default methods, and abstract methods.
Communication: One of the functions of the interface is to facilitate communication. You can declare how the methods and fields of a given type should work through the interface.
Multiple Inheritance: Java does not provide multiple inheritance, however you can achieve multiple inheritance using interfaces.
Abstraction: Abstraction is the process of shielding the user from the implementation specifics in order to merely supply them with the functionality. To put it another way, the user will know what the object does rather than how it does it. Since all of the interface's methods are abstract, just the method signature and prototype are known to the user. You can achieve (full) abstraction via interfaces.
Coupling: The phrase coupling refers to how one class depends on another. Therefore, while using an interface, we define the method and signature independently. In this technique, Loose Coupling is archived and all methods and classes are completely independent.
The interface keyword is used to declare an interface. An interface's public, static, and final properties are all set to their default values, and its methods all have an empty body. A class that implements the interface is required to implement each of its functions.
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
An interface can have as many methods as necessary, just like a class.
The interface is written in a file with a.java extension, just as classes.
Unexpectedly, an interface's bytecode will have surfaced in a.class file.
An interface is displayed as a package, and the corresponding bytecode is located in a directory with the same name as the package.
You can instantiate variables and make objects in a class. You cannot instantiate a variable and produce an object in an interface.
A class may include concrete methods that have implementation. The interface is not permitted to include concrete (implementation-ready) methods.
Classes employ the access specifiers private, protected, and public. Interface only uses the Public specifier.
Abstract class | Interface |
---|---|
Both abstract and concrete methods can be found in abstract classes. | There can only be abstract methods on an interface. Starting with Java 8, it is possible to have both default and static methods. |
An interface can be implemented by abstract classes. | Interface can only extend another interface; it cannot implement another interface. |
Any type of member, such as private or public, can be included in an abstract class. | All members of an interface must be public. |
Several inheritance occurs when a class implements multiple interfaces or when an interface extends multiple interfaces.
interface Interface1{ public static int num = 100; public default void display() { System.out.println("display method of Interface1"); } } interface Interface2{ public static int num = 1000; public default void display() { System.out.println("display method of Interface2"); } } public class InterfaceDemo implements Interface1, Interface2{ public void display() { System.out.println("This is the implementation of the display method"); } public void show() { Interface1.super.display(); Interface2.super.display(); } public static void main(String args[]) { InterfaceDemo obj = new InterfaceDemo(); obj.show(); } }
A marker or tagged interface is one that has no members; examples are Serializable, Cloneable, Remote, etc. They are used to give the JVM some necessary data so that it can execute certain helpful operations.
Built-in marker interfaces in Java are interfaces that are already available and ready to use within the JDK. Among the numerous built-in marker interfaces are the following:
Cloneable Interface
Cloneable Interface: Cloneable Interface is a marker interface in the Java programming language. It is a part of the java.lang package. It is used to duplicate an item and give it a different name. A class must implement the Cloneable interface if we wish to be able to copy its objects. This is used to tell the JVM that objects of the class that have implemented the Cloneable Interface can use the clone() function of the Object class.
import java.lang.Cloneable; . class E1 implements Cloneable { int idx; String strs; public E1(int idx,String strs) { this.idx = idx; this.strs = strs; } // Overriding clone() method // by simply calling Object class // clone() method. @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } public class Demo { public static void main(String[] args) throws CloneNotSupportedException { E1 a = new E1(20, "logicmojo"); E1 b = (E1)a.clone(); System.out.println(b.idx); System.out.println(b.strs); } }
Serializable Interface: Java's Serializable Interface is a Marker Interface, which means that it is empty because it lacks any methods, fields, constants, etc. The Java IO package contains a definition of it.
import java.io.*; class E1 implements Serializable { int idx; String strs; public E1(int idx,String strs) { this.idx = idx; this.strs = strs; } } public class Demo { public static void main(String[] args) throws IOException, ClassNotFoundException { E1 a = new E1(100,"logicmojo"); FileOutputStream fos = new FileOutputStream("abc.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(a); FileInputStream fis = new FileInputStream("abc.txt"); ObjectInputStream ois = new ObjectInputStream(fis); E1 b = (E1)ois.readObject(); System.out.println(b.idx+" "+b.strs); // closing streams oos.close(); ois.close(); } }
Remote Interface: A Java marker interface called Remote Interface is specified in the java.rmi package. It serves the purpose of remote method invocation.
Crack your next tech interview with confidence!
Multiple Java Interfaces can be implemented by a Java class. All of the methods declared in the interfaces must be implemented by the class.
Every abstract method declared in the interface should be overridden by the class.
An object can be messaged using the interface without worrying about the class it belongs to.
The methods in the interface must have functionality, which the class must supply.
The methods of an interface are implicitly public and abstract.
An interface cannot be instantiated.
A reference to an interface may point to its implementing classes' objects.
One or more interfaces may extend from one interface. A class can implement any number of interfaces but can only extend one other class.
It is impossible for one interface to implement another. If necessary, it must extend another interface.
Nested interfaces are interfaces that are specified within of other interfaces.
Interface variables must be initialised at declaration time. The compiler will throw an error otherwise.
Java does not allow a class to implement two interfaces with identical methods but distinct return types.
It is necessary to implement the compare(Object o1, Object o2) method of the Comparator interface, which accepts two Object arguments. The method should be implemented in a way that it returns a negative integer if the first argument is smaller than the second, a zero value if they are equal, and a positive integer if the first argument is larger than the second. Generics are used by the Comparable and Comparator interfaces to perform compile-time type verification.
public class PRankComparator implements Comparator<Player> { @Override public int compare(Player fPlayer, Player secPlayer) { return Integer.compare(fPlayer.getRanking(), secPlayer.getRanking()); } }
public class PAgeComparator implements Comparator<Player> { @Override public int compare(Player fPlayer, Player secPlayer) { return Integer.compare(fPlayer.getAge(), secPlayer.getAge()); } }
PRankingComparator playerComparator = new PRankingComparator(); Collections.sort(volleyballTeam, playerComparator);
Output:
Before Sorting: [B, A, D]
After Sorting: [A, B, D]
The process of declaring an interface inside of another existing interface or a class is known as interface nesting. An Inner Interface is another name for the Nested Interface.
Direct access to the Nested Interface is not possible. In order to resolve the Namespaces by grouping them with their respective Interfaces and Classes, nesting is implemented. Using this method, we can call the nested interface by using the name of the outer class or outer interface, a dot (. ), and the interface name.
class Automobile { interface Activity { void move(); } } class Bike implements Automobile.Activity { public void move() { System.out.println("Bike is Automobile"); } } public class Tester { public static void main(String args[]) { Bike honda = new Bike(); honda.move(); } }
We can achieve total abstraction thanks to interfaces.
An application can achieve loose coupling by using interfaces. This indicates that the implementation of the other class is unaffected by changes made to the first one.
Interfaces can be used to simplify complicated architectures and make object dependencies obvious.
Multiple inheritances can be implemented via interfaces.
Since they must be made public, interfaces disclose their member variables. This could cause problems with testing and forecasting the behaviour of your code (and the same reasons why one should avoid making class member variables public).
In some circumstances, changing an interface could result in unforeseen behaviour for the classes that implement it since an interface can be thought of as a contract that is implemented by numerous classes. For instance, if a new method is added that is not the default, if the old classes do not implement that method, compilation issues will be raised. Interfaces ought to be immutable in order to prevent this as much as possible (this could be a disadvantage in certain situations, too).
One interface could contain several methods that may not all be required for a class if interfaces are not carefully developed. This could result in an empty implementation for these methods, making your code verbose. Interfaces must be properly developed with the Interface Segregation Principle in mind in order to avoid this.
Functional Interface
Marker Interface
Functional Interface
An interface that just has one abstract method is said to be functional. They are only capable of displaying one functionality. Lambda expressions can be used to represent an instance of a functional interface starting with Java 8. Any number of default methods can be included in a functional interface. Some examples of useful interfaces are Comparable, Runnable, and ActionListener.
Functional interfaces don't require the use of the abstract keyword because the method defined inside the interface is abstract solely by default, making its use optional. Lambda expressions are another example of a functional interface.
Marker Interface
An interface is referred to as a Marker interface if it lacks any methods, fields, Abstract Methods, and Constants. Additionally, an interface is referred to as a marker interface if it is empty. Examples of Marker interfaces include the Serializable and Cloneable interfaces.
A complete abstraction of a class is an interface. By default, every data member in the interface is public, static, and final. If any static final fields are not initialised in the default constructor at the time of declaration, a compilation error will be raised and the variable variable Name will not be initialised.
Since the methods inside an interface are by default public abstract, the implementing class must be used to give the method implementation rather than the interface itself. Consequently, there is no requirement for a constructor inside the interface.
There are no non-static data members in the interface, hence there is no need for a constructor, which is needed to initialise non-static data elements.
There is no implementation of the methods that are contained in the interface, hence there is no need to create objects to call the methods, rendering the constructor in the interface redundant.
A compile-time error will be generated by the compiler if we try to add a constructor inside the interface.
1. The interface could not describe the implementation before JDK 8. Now that interface methods have default implementations, we can add them. This default implementation serves a specific purpose and has no bearing on interfaces' original design.
Let's say an existing interface needs a new function added to it. Since the classes have not yet added those new functions, it is obvious that the old code will not function. Therefore, we will provide a default body for the newly added functions using default implementation. the previous codes will still function.
We may now specify static methods in interfaces that can be invoked independently without an object, which is another capability that was added in JDK 8. The fact that these methods are not inheritable.
Interfaces can now contain the following starting with Java 9: Static methods, Private methods, Private Static methods
Generics force all (reference) types that are passed in dynamically as parameters to be taken into account by a class, interface, and method. That guarantees type safety. After the class name as of the instance variable, generic class parameters are supplied in angle brackets "<>".
The interfaces in Java that deal with abstract data types are known as generic interfaces. Java collections can be independently manipulated with the aid of interfaces, regardless of representational details. They are accustomed to creating hierarchies in Java via multiple inheritance. The Java class is not the same as them. These only have static and final variables and include all abstract methods. Not objects, but only interfaces can be referenced. These lack constructors and instance variables, in contrast to classes. The word "implements" is relevant here. These resemble generic classes in many ways.
package java.lang; import java.util.*; public interface Comparable<T> { public int compareTo(T o); }
Constants may be present in a Java interface. Constant definition in an interface may make sense in some circumstances. especially if the classes that implement the interface will utilise those constants for calculations or as inputs for some of the interface's methods. But if you can, try to stay away from using variables in Java interfaces, is my suggestion to you.
Even if you omit the terms "public," "static," and "final" from the variable declaration, all variables in an interface are automatically public, static, and final.
Here is an illustration of a Java interface with two declared constants:
public interface MyInterface { int FALSE = 0; int TRUE = 1; }
Default methods are implicitly public, just like standard interface methods; the public modifier is not required.
They differ from standard interface methods in that they give an implementation and are declared with the default keyword at the start of the method signature.
public interface MyInterface { // regular interface methods default void defaultMethod() { // default method implementation } }
The inclusion of default methods in the Java 8 version makes sense.
When one or more methods are introduced to an interface in a typical abstraction-based architecture with one or more implementations, all of the implementations
are required to implement them as well. If not, the design will just fail.
Default interface methods are a practical solution to this problem. They give us the ability to extend an interface with new methods that are built-in to implementations. Consequently, there is no need to change the implementing classes. Backward compatibility is elegantly maintained in this fashion without the need to refactor the implementers.
With this article at Logicmojo, you must have the complete idea of interface in Java.