what is interface in java

11 months ago 25
Nature

An interface in Java is an abstract type that is used to declare a behavior that classes must implement). It is a blueprint of a class that contains static constants and abstract methods. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final) ). All methods of an interface do not contain implementation (method bodies) as of all versions below Java 8. Starting with Java 8, default and static methods may have implementation in the interface definition. Then, in Java 9, private and private static methods were added).

A class that implements an interface must implement all of the non-default methods described in the interface, or be an abstract class). Object references in Java may be specified to be of an interface type; in each case, they must either be implemented by objects of a specific class or defined as null). Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If a class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

The advantages of using interfaces in Java are as follows:

  • Without bothering about the implementation part, we can achieve the security of the implementation.
  • In Java, multiple inheritances is not allowed, however, you can use an interface to make use of it as you can implement more than one interface.

Since Java 8, interfaces can have default and static methods which is discussed later. The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and final keywords before data members. In other words, Interface fields are public, static and final by default.