Showing posts with label Interface. Show all posts
Showing posts with label Interface. Show all posts

Monday, July 5, 2010

Interface Basics

An interface is a reference type, similar to a class that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. They act as a skeleton for implementing classes specifying what to implement and not how to implement them.

Interfaces add most of the functionality that is required for many applications which would normally resort to using multiple inheritance in a language such as C++.

Defining Interfaces

access interface name /* access is either public or not used (default) */

{
type final-varname1 = value; /* static final implied */ /* must be initialized with a constant value*/
type final-varname2 = value;
return-type method-name1(parameter-list); /*abstract methods */ /* no body */
return-type method-name2(parameter-list);
...
} /* All methods and variables are implicitly public if the interface, itself, is declared as public. */

Implementing Interfaces

access class classname [extends superclass] [implements interface [,interface...]]
/* access is either public or not used. (default)*/

{
public return-type method-name(parameter-list) /* methods that implement an interface must be declared public.*/
{
// method body   
/*type signature of the implementing method must match exactly the type signature specified in the interface definition. */
}
}

If a class implements two interfaces that declare the same method, then the same method will be used by clients of either interface.

Partial Implementations of Interfaces

If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract.

Extending Interfaces

Interfaces can extend other interfaces. A single interface can extend multiple interfaces.


Interface Iface1 extends Iface2, Iface3

{ ………….}

Sub-interfaces cannot define methods declared in the super-interfaces. Class implementing the derived interface must implement all methods.

Difference between abstract class and interface

Interface
Abstract class
Interfaces can not implement any methods. i.e. All methods are abstract.
Abstract class can implemented some of its methods. i.e. Some methods may not be abstract.
Cannot contain constructors.
Can contain constructors.
Can be implemented by classes or extended by other interfaces.
Can be extended by classes only.
Classes may Implement  several interfaces
Classes can extend only one abstract class.
Class implementing an interface has to implement all the methods of the interface
Class extending an abstract class does not need to  implement all the methods of the abstract class.
Access specifier is either public or default.
Any access specifier can be used.