Java interface with example

Java Interface with examples:-

Let’s talk about Java interface with example.An interface is a reference type, similar to a class, which can contain only constants, method signatures, default methods, static methods, and nested types. An interface is like a blueprint of class, it has static constant and abstract methods only. By using interface we can achieve fully abstraction in Java and it also represents IS-A relationship. It cannot be instantiated just like an abstract class. The interface keyword is used to declare an interface.

Use of Java Interface

  • By using we can achieve fully Abstraction.
  • The java interface supports multiple inheritance.
  • Used a lot in creating design patterns.
  • It can be used to achieve loose coupling.

Example :
Below given is an example of an interface:

Implementing an Java Interface:

As an example given below, a class implements an 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.

An java interface cannot implement another interface. It has to extend the other interface if required. An interface uses the extends keyword to implement an interface.

Important key points about Java interface :

  • In interface can be created by interface code.
  • We can achieve full abstraction by using interface.
  • The Java interface supports multiple Inheritances.
  • An interface can’t extend any class but it can also extend another interface.
  • A class can implement interface By using implements keyword.
  • We can’t create an object of the interface in java.
  • An interface doesn’t contain any constructor.
  • By default, any attribute of the interface is public, static and final.
  • A class can extend more than one Interface.
  • An interface can extend another Interface.

Advantages of Interface :

  • An interface provides a polymorphic behavior.
  • By using interface we can achieve multiple inheritance.
  • By using interface we can create a loosely coupled application.
  • Interfaces are good for starting point to define Type and create a top level hierarchy in our code.

The disadvantage of Java interface :

  • As you saw Interface Example In Java, We need to choose interface methods very carefully at the time of designing our project because in future we can’t add of remove any methods from the interface.
  • Java interfaces are slower and more limited than other ones.

Related Posts :-

 

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons