Interface in java

What is an Interface?

An interface is a description of a set of methods that conforming implementing classes must have. An interface may never contain method definitions.

One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class. A Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.

Can we create an object for an interface?

Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.

Do interfaces have member variables?

Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example.

What modifiers are allowed for methods in an Interface?

Only public and abstract modifiers are allowed for methods in interfaces.

Note:

  • You can’t mark an interface as final.
  • Interface variables must be static.
  • An Interface cannot extend anything but another interfaces.
  • Methods in an interface are implicitly public.
//Filename: Sports.java
public interface Sports
{
   public void setHomeTeam(String name);
   public void setVisitingTeam(String name);
}

//Filename: Cricket.java
public interface Cricket extends Sports
{
   public void homeTeamScored(int runs);
   public void visitingTeamScored(int runs);
}

//Filename: Hockey.java
public interface Hockey extends Sports
{
   public void homeGoalScored();
   public void visitingGoalScored();
   public void overtimePeriod(int time);
}

The Cricket interface has two methods, but it inherits two from Sports. Thus, a class that implements Hockey needs to implement all four methods.
Similarly, a class that implements Hockey needs to define the three methods from Football and the two methods from Sports.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation