Saturday, May 21, 2011

Interface in Java

Interfaces can be used to implement the Inheritance relationship between the non-related classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy.  Using Interface, you can specify what a class must do but not how it does.
  1. A class can implement more than one Interface.
  2. An Interface can extend one or more interfaces, by using the keyword extends.
  3. All the data members in the interface are public, static and Final by default.
  4. An Interface method can have only Public, default and Abstract modifiers.
  5. An Interface is loaded in memory only when it is needed for the first time.
  6. A Class, which implements an Interface, needs to provide the implementation of all the methods in that Interface.
  7. If the Implementation for all the methods declared in the Interface are not provided , the class itself has to declare abstract, other wise the Class will not compile.
  8. If a class Implements two interface and both the Intfs have identical method declaration, it is totally valid. 
  9. If a class implements two interfaces both have identical method name and argument list, but different return types, the code will not compile.
  10. An Interface can’t be instantiated. Intf Are designed to support dynamic method resolution at run time.
  11. An interface can not be native, static, synchronize, final, protected or private.
  12. The Interface fields can’t be Private or Protected.
  13. A Transient variables and Volatile variables can not be members of  Interface.
  14. The extends keyword should not used after the Implements keyword, the Extends must always come before the Implements keyword.
  15. A top level Interface can not be declared as static or final.
  16. If an Interface species an exception list for a method, then the  class implementing the interface need not declare the method with  the exception list.
  17.  If an Interface can’t specify an exception list for a method, the class can’t throw an exception.
  18.  If an Interface does not specify the exception list for a method, the class can not throw any exception list.
The general form of Interface is
Access interface name {
         return-type method-name1(parameter-list);
            type final-varname1=value;
Marker Interfaces :  Serializable, Clonable, Remote, EventListener

Marker Interface is an Interface which does not have any method declarations. They are used to mark/tag the nature of the class. 

Click here to More about Abstract class
Click here for more about Difference between Abstract class and Interface

No comments: