Sunday , October 21 2018
Home / Java / Interface in Java

Interface in Java

An interface is a reference type in Java, it is similar to class, it is a collection of abstract methods. An interface in java is a blueprint of a class. It has static constants and abstract methods only.

The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

Advantages of Interface:

  • It is used to achieve fully abstraction.
  • By interface, we can support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling.

Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an interface:

Interfaces have the following properties:

  • An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface.
  • Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
  • Methods in an interface are implicitly public.

Interface Implementation:

interfacerelation

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

 

xtending Interfaces:

An interface can extend another interface, similarly to the way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.

 

Extending Multiple Interfaces:

multipleinheritance

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

For example, if the Hockey interface extended both Sports and Event, it would be declared as:

 

About admin

Check Also

Internal Working of HashMap in Java

In this article, we will see how hashmap’s get and put method works internally. What ...

Leave a Reply