Interfaces

         An Interface is one which contains the set of abstract methods, or Interface is similar to class which contains the set of variables and methods. Interfaces are declared using the interface keyword, and may only contain method signature and constant variable declaration. An interface may never contain method definition. 
        All the methods in the interface are abstract, even if we did not declare the method as abstract, by default Java compiler declares the methods as abstract. The variables in the interface are declared as static and final. The following is the syntax of interface:

Interface Syntax
Fig1: Interface Syntax
         It is not mandatory to provide variables in the interface, it is based on the requirement. Now, let us see an example on interface.

Interface Example
Fig2: Interface Example
         When we observe the above interface, there we haven't declared variables as Static & final and methods as abstract. Now, when we compile this interface compiler automatically declares the variables as public, static and final, and methods as public abstract

The following are the rules of Interfaces:  
  • All interface methods are implicitly public and abstract.
  • All variables that are defined in an interface must be public , static and final
  • Interface methods must not be static
  • Interface methods cannot be marked as final.
  • An interface can extend one or more interfaces.
  • An interface cannot extend anything other than interface.
  • An interface cannot implement another interface or class. 
           Anybody can release the interface, Once if the interface is released anybody can provide the implementation. We will provide implementation to the interface using a class. Providing the implementation means, defining(writing the method body) all the abstract methods present in that interface. When a class implements an interface it must define all the abstract methods of that interface. If we don't want to provide the definition to all the methods, then we should declare that class as abstract, otherwise compiler reports an error message.            

           We cannot create an object to the interface, but we can create a reference variable. This reference variable can hold the object of a class which provides the implementation of that interface.                  
          

No comments:

Post a Comment