Java Tut – Interface

Interface is a collection of abstract methods.A class implements an interface, thereby inheriting the abstract method of the interface.
Declaring Interafces:

interface keyword is used to declare an interface.simple example:

Implementing/Declaring Interfaces:
– An interface is implicitly abstract.You do not need to use the abstract keyword while declaring an interface.
– Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
– Methods in an interface are implicitly public.

example:
Animal.java

Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific of the behaviors of the iterafce, the class must declare itself as abstract.

A class uses the implements keyword to implement an interface.Thje implements keyword appears in the class declaration following the extends portion of the declaration.
example:
MammalInt.java

Output:

When overriding methods defined in interfaces there are several rules to be followed:
– Checked exceptions should not be declared on implementation methdos other than the ones declared by the interface method or subclasses of those declared by the interface methods.

– The signature of the interface method and the same retrun type or subtype should be maintained when overriding teh methods.

– An implementation class itself can be abstract  and if so interface methods need not to implemented.

When implementation interfaces there are several rules:
-A class can implement ore than one interface at a time.
– A class can extend only one class,but implement many interfaces.
-An interface can extend another interface,similarly to the way that a class can extend another class.

Extending Interfaces:

An interface can extend another interface, similarly to the way that a class can extend another class.The extends keyword is used to extend an intrerface, and the child interface inherits the methods of the the parent interface.

The following sports interface is extended by Hockey and Footbal interfaces.
Filename: Sports.java

The hockey interface has four methods, but it inherits two from Spors;
thus a class that implements Hockey need to implement all six methods.Similarly, a class that implements Football need to define the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces:
An interface is not class so Interface can extend more than one parent interface.
example:

Tagging Interfaces:
the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is:

An interface with no methods in it is referred to as a tagging interface.There are two basic design purposes of tagging interfaces
Creates a common parent:

Adds a data type to a class:

Reference:
http://www.tutorialspoint.com/java/java_interfaces.htm