Interface


Interface

It is defined as an abstract type used to specify the behavior of a class. The interface consists of static constants and abstract methods. Multiple interfaces cannot be implemented by a java class. Interfaces are declared using the interface keyword. The methods inside the interface are implicitly public and abstract.

Syntax:

Interface
{
//methods
}

    The Java interface can only have abstract methods, not method bodies. In Java, it is used to achieve abstraction as well as multiple inheritance. To put it another way, interfaces can have abstract methods and variables. It isn't allowed to have a method body.

Some key points about the java interface::

  • A class that implements an interface is required to implement all of the interface's functions.
  • Because of the uncertainty, multiple inheritance is not allowed in the case of classes. However, because there is no uncertainty in the case of an interface, it is supported. It's because the implementation class handles the implementation.
  • A class implements an interface, but one interface extends another.

Marker Interface or Tagged Interface:

A marker or tagged interface has no members, such as Serializable, Cloneable, Remote, etc. They're used to give the JVM some crucial information so that it can conduct some essential tasks.

Example:

Com.knowledge2life interface inter { public void animalSound(); public void sleep(); } class inter1 implements inter { public void animalSound() { System.out.println("Knowledge2life"); } public void sleep() { System.out.println("website"); } } class Main { public static void main(String[] args) { inter1 myPig = new inter1(); myPig.animalSound(); myPig.sleep(); } }

OUTPUT:

knowledge2life
website