/* related posts with thumb nails */

Interface in Java & its implementation:

An interface is a list of methods that must be defined by any class which implements that interface. It may also define constants (public static final). Interfaces are declared using the interface keyword, and may only contain method signatures and constant declarations. An interface may never contain method definitions.

· The class which implements an interface must implement all of the methods described in the interface, or be an abstract class.

· As interfaces are implicitly abstract, they cannot be directly instantiated except when instantiated by a class which implements the said interface.

· In an interface, all methods are implicitly public.

· In an interface, all variables are static and final by default

· A class can implement many different interfaces.

· One interface can extend another interface.

· A class can simultaneously extend a class and implement multiple interfaces

· One benefit of using interfaces is that they simulate multiple inheritances.

Interfaces are defined with the following syntax

[visibility] interface InterfaceName [extends other interfaces]

{

constant declarations

method declarations

}

The following program demonstrates the usage of interface. It has a constant named BORDER_WIDTH and a method named ‘draw()’. The class ‘Rectangle’ is implementing the interface and thus providing definition for the method ‘draw()’.

interface Shape

{

int BORDER_WIDTH = 5;

void draw( );

}

class Rectangle implements Shape

{

void draw()

{

…….

}

}

class Test

{

public static void main(String as[])

{

Shape s1;

s1=new Rectangle();

s1.draw();

}

}

Related Topics:

0 comments:

Post a Comment