Java Interfaces

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. It is an interface through which multiple inheritance is implemented in Java. We can implements more than one interfaces in Java.
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.  
one thing to be notice:

Class implements interfaces and interfaces extends  interfaces.
Class implements more than one interface and interface extends more than one interface.
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an interface:
interface Animal{
void eat();
void travel();
Interfaces have the following properties:
1.An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface.
2.Each method in an interface is also implicitly abstract, so the abstract keyword is not needed
3.Methods in an interface are implicitly public.

Implementing Interfaces:
class Mammal implements Animal{
public void eat(){
 System.out.println("Mammal eats");
public void travel(){
System.out.println("Mammal travels");
public static void main(String args[]){
      Mammal m = new Mammal();;;
Mammal eats
Mammal travels
The class which implements the interface is necessary to implements its all methods..
Another definition of interface is:
An interface is a list of methods that must be defined by any class which implements that interface.
Interfaces can extend several other interfaces, using the same formula as described below. For example
public interface A extends B, C
//interface  body

People who read this post also read :


The point 4 above:
"4.Variables declared in interface is implicitly final or static but not both together."
is incorrect
Variables declared in an interface are always public static and final.

Post a Comment


Twitter Delicious Facebook Digg Stumbleupon Favorites More