Interface in Java

java-tutorial

Sharing is caring!

Step 1:Methods form the object’s interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the “power” button to turn the television on and off.

Step 2:Interfaces are collection of abstract methods with no definition.

Step 3:It  is not a class.

Step 4.It  differes from class.But there are certain simiarities too between interface and class.

Similarities of Interface and class:

Step 1 :Interface can contain any number of methods to it.

Step 2: Bytecode will be appeared in .class file.

Step 3:Interface is written in a file with extension .java.

Dissimilarities of Interface and class:

Step 1:It cannot be instantiated.

Step 2:It  does not contain any constructor method.

Step 3 :All  methods will be of abstract type.

Step 4:It cannot be extended by a class.It is implemented by a class.

Step 5:It can extend multiple interfaces.

 

Syntax for interface:

{code type=”java”}
/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements

public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}
{/code}
Example of interface:
{code type=”java”}
interface Animal {

public void eat();
public void travel();
}

public class MammalInt implements Animal{

public void eat(){
System.out.println(“Mammal eats”);
}

public void travel(){
System.out.println(“Mammal travels”);
}

public int noOfLegs(){
return 0;
}

public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
{/code}

 

Sharing is caring!