INTERFACE IN JAVA

 

Interface in Java







The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java .An interface in Java is a blueprint of a class. It has static constants and abstract methods.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.


Why use Java interface?

There are mainly three reasons to use interface. They are given below.

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


How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.








interface is considered as 100% pure abstract class.



Since java 8, interface can have default method and static method .


Eg

interface Animal {
  
public void animalColor(); // interface method 

}

class Dog implements Animal {

  public void animalColor() {

    // The body of animalColor() is provided here

    System.out.println("The dog color is black ");

  }




Comments

Popular posts from this blog

OBJECT ORIENTED CONCEPTS

Arrays programms