Skip to content

Interface in Java

Reading Time: 2 minutes

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}


 

Methods can be declared in base class and its definition will be 
implemented in its derived class.

Output:
Mammal eats
Mammal travels.


Points to remember:
1.An interface is abstract by default.You do not need to use abstract keyword explicitly.
2.Methods are implicitly public.


Extending Interface:
{code type="java"}
public interface Sports
{
   public void setHomeTeam(String name);
   public void setVisitingTeam(String name);
}

//Filename: Football.java
public interface Football extends Sports
{
   public void homeTeamScored(int points);
   public void visitingTeamScored(int points);
   public void endOfQuarter(int quarter);
}

//Filename: Hockey.java
public interface Hockey extends Sports
{
   public void homeGoalScored();
   public void visitingGoalScored();
   public void endOfPeriod(int period);
   public void overtimePeriod(int ot);

}


{/code}

See also  Top 25 Magento Themes 2017
Tags:

Leave a Reply