Pages

Friday, August 3, 2012

Interface

An Interface is collection of methods with empty bodies.
Interface contains only

  • static and final fields.
  • abstract methods.

Interface is declared as

interface abc
{
     //static & final fields
     //empty body methods are declared here.
}

Constraints:

  • An interface can contain only abstract methods and any class implementing the interface thereby inherits the abstract methods of the interface.
  • Unless the class that implements the interface is abstract,all the methods of the interface must be defined in the class. 
Comparison between a normal class and interface:

classinterface
can have constructorsdon't have any constructor
can be instantiatedcan't be instantiated
is extendedis implemented

how to implement an interface ?

here is a sample code

interface Vehicle
{
         public static final int speed;
         public void displayInfo();
}
class Car implements Vehicle
{
         speed=150;
         public void displayInfo()
         {
               System.out.println("it's a car");
          }
}

No comments:

Post a Comment