Java Interface Explanation for beginners

Interfaces

Using the keyword interface, you can fully abstract a class interface from its implementation. Using interface in java you can specify what a class must do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance variables.

To implement an interface , a class must provide the complete set of methods required by the interface. Each class is free to determine the details of its own implementation.interface are designed to support dynamic method resolution a run time.

What is the reason for using interfaces in java?

Generally,in order for a method to be called from one class to another,both classes need to be present at compile time. This requirement by itself makes for a static and nonextensible classing enviroment.To avoid this problem java introduced the interfaces they disconnect the definition of a method dor set of methods from the inheritance. Since interface are in a different hierarchy from classes. Hence one class can implement any number of interfaces.This is where the real power of interface.This the reason for using interface in java.

Defining a Interface

An interface ia defined like a class.

General form of interface:
access interface name {
    return_type method_name(parameter_list);
    type final varname=value;
}

The interface is only available to other members of the package in which it is declared. When it is declared as public, the interface can be used by any other code.In this case,the interface must be the only public interface declared in the file, and the file must have the same name as the interface. The methods that are declared have no bodies. THey end with a semicolon after the parameter list. Each class that includes such an interface must implement all of the methods.

Given below example is a simple interface that contains one method called callback() that takes a single integer parameter.

interface Callback()   {
    void callback(int a);
}
  

Leave a comment