Skip to main content

Interface in Java

Introduction:

Prerequisites:

  • Abstraction in Java
  • Inheritance in Java
Multiple inheritance is a process in which a class inherits two other parent class, taking the benefits of the two classes. However, Java doesn't support multiple inheritance. Multiple inheritance sometimes creates problems for the programmers to understand the codes and inheritance procedure. So, Java's solution to this problem is called interface. Interface in Java is nothing but a collection to method declaration. Interface is basically a kind of class. Like classes, an interface contains members and method, unlike classes, in interface all members are final and all methods are abstract. However an interface can contain non- abstract method.

Interface Concept:

An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. That is, the interface is a collection of behaviors that can be implemented by any class in any Java program. It is a set of method but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior. An interface is named collection of method definition without implementation. Interface reserve behaviors for classes that implement them. Methods declared in an interface are always 'public' and 'abstract'. The Java compiler(javac) will not complain if you omit both the keywords(i.e., 'public abstract'). The 'static methods' be cannot declared in the interfaces, as these methods are never abstract and do not express behavior of objects. However other members are public, final, static.

Interface Declaration:

    An interface can be declared using a keyword known as 'interface'.
    Syntax used:
                    interface <interface_name>{
                        public abstract <method_name>();
                    }
    An interface is syntactically similar to classes, but they lack instance variables, and their methods are defined without any body.
    For example:

             interface Say_Hi{
                    public abstract Hi(int H) ;
                    void call_me(int c);
             }

Multiple inheritance using interface:

    Once an interface is defined, any number of classes can implement that interface.
                               [Interface]
                                     /   \
                          [class 1][class 2]

    Also, one can implement any number of interfaces using a class.
                                            [class]
                                           /    |    \
                                         /      |      \
                                       /        |        \
                                     /          |          \ 
                    [interface 1][interface 2][interface 3]

Properties of interface :

  • Interface must be declared with the keyword 'interface'.

  • All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but method is still always public and abstract by default.

  • All the variables defined in an interface is public-static-final. In other words, interfaces can declare only constants, no instances variables.

  • Interface methods must not be static. Because interface methods are abstract, they cannot be marked final.

  • An interfaces can extend one or more other interfaces.

  • An interface cannot implement another interface or class, but can extend other classes.

  • An interface types can be used polymorphic-ally.

Syntax for defining interface:

    Following is the syntax to define an interface:
        interface <interface_name> extends <other_interfaces.....]{
            [variable(s) declaration;]
            [Method(s) declaration;]
        }
    Variable in an interface is declared as :
        static final <type> <variable_name> = <value>;

    Method in interface is declared as :
        <return_type>  <method_name> (parameter list);

Example:

        interface anItem{
            static final int code = 101;
            static final String itemName = "SHEELA";
            void recordEntry();
        }

Inheritance in Interface:


  • Interface can inherit from other interface, i.e., interfaces can be inherited from the other         interfaces.


            interface Constants{
                double speed = 120;
                String unitOfSpeed = "kmph";
                ....... ........ ..........
            }
            interface physics{
                void NewtonLaw();
            }
            interface Chemistry extends Constants{
                ''''''''' '''''''' '''''''''' ;
                ''''''''' '''''''' '''''''''' ;
            }


  • Interface can also multiply inherits, i.e., interface can inherit other interfaces.


            interface lawOfphysics extends Constants, physics{
                '''''''''''''' '''''''''''''' '''''''''''' ;
                '''''''''''''' '''''''''''''' '''''''''''' ;
            }

Standard Interfaces in Java:

    Java has some standard interfaces defined and are mostly used interfaces. They are:
        1.) Iterator,
        2.) Cloneable,
        3.) Serializable,
        4.) Comparable.

    1.) Iterator:

  • Iterator is an interface defined in java.util.*; package which is used to run through a collection of objects without knowing how the objects are stored, for example, in array, list, bag, or set.

  • This interface has few methods like:-

    • public abstract boolean hasNext():
      • this method checks whether the list has more element or not, if yes then true, else false.
    • Object next():
      • this method returns the next element in the list or collection.
    • void remove():
      • this method is an optional, we can use it or cannot be used.This method throws some exception.

    2.) Cloneable:

  • Cloneable is another interface defined in Java which can be used to make a copy of an existing object via the 'clone()' method on the class 'Object'.

  • This interface does not contain any methods.

  • It basically returns an identical copy of an object. The copy can be of two types:-
    • Deep copy-a physical copy of all the objects,class variables, instance variables are made and it is most preferable.
    • shallow copy-by default(logically) copy of any object is made.
  • The clone() method can be used to control the duplicacy of the objects. For example, database lock or open file reference.

  • clone() method should throw an exception called 'cloneNotSupportedException' if the Cloneable interface does not work.

    3.) Serializable:

  • Serializable is an interface defined in java.io.*; . It is used to send or communicate a Pack of web objects over a network or to store in a disk and can be restored later as a web of objects 'Comparable'.

  • A class X that implements the Serializable interface tells clients that X objects can be stored on a file or other persistent methods.

    4.) Comparable:

  • Comparable is also an interface defined in java.util.*; to make a total order of objects, for example, 3, 56, 67, 879, 3422, 34234.

Comments

Popular posts from this blog

Java Packages

Packages In Java: Package is a container for the classes that are used to keep the class name space compartmentalized. In other words,  Java Packages are nothing more thanthe way we organize files into different directories according to their functionality, usability as well as category they should belong to. A Java package is a Java programming language mechanism for orgranizing classes into name spaces. Example: You can contain all classses related to all sorting programs in your own package. We can keep different classes of same type in a same package for better glance of the project. It allows fexibility to give same name but to many classes, that is to avoid name space collision . The packages in Java provides mechanism for partitioning the class name space into more manageable chunks. Infact, package is both a naming and a visibillity control mechanism. It supports reusability and maintainability of the Java codes. Advantages of Packages: Packages prov...