| Mobile | RSS

Java Tutorial : Implementing Interfaces 

13th Sep, 2009 | No Comment | Posted in Java by Alex Jose

There might be cases where you might need to inherit the features of more than one class. But Java does not support multiple inheritance. However, you can simulate multiple inheritance in Java by using interfaces.

An interface is a collection of methods and data members that can be implemented by any number of classes residing in a class hierarchy. Interface is known as a prototype for a class. Methods defined in an interface are only abstract methods.

An abstract method contains only the declaration for a method without any implementation details. The implementation of an abstract method is defined in the class implementing the interface. You can implement multiple interfaces in a single class.

Interfaces contain a set of abstract methods and static data members. However, an interface does not include any method implementations, but only method definitions. The syntax to define an interface is:

interface <interfacename>
{
//interface body
static final data members;
return type public methods(parameters);
}

You can implement an interface in one or more than one class before defining it. The public access specifier must be specified with the methods declared in the interface. The syntax to implement an interface in a class is:

class <class_name> extends [superclass] implements [interfacename]
{
//Defining the method declared in the interface.
return type public methods(parameters)
{
//Body of the method
}
}

In the preceding syntax, a class that extends from a superclass implements an interface using the implements keyword. The class defines the methods that are declared in an interface.

When you declare data members in an interface, these are always treated as final. You cannot reassign values to the data members in the class where you implement the interface. Use data members in an interface only if you need a constant value for the data members across the classes in which you implement the interface.

Related Posts with Thumbnails