by Dinesh Thakur Category: Introduction to Java

Java expands the concept of abstract classes with interfaces. An interface is similar to an abstract class. However, it contains only abstract methods and constants (final fields). It specifies what must be done but not how. Once an interface is defined, class implements an interface by providing an implementation for each method declared by the interface. Also one class can implement any number of interfaces. Interfaces have the following advantages.

• Interfaces are easier to work with than inheritance because you do not have to worry about providing any implementation details is the interface.
• Interfaces facilitate multiple inheritance which is not possible with classes .
• Interfaces allow objects of unrelated classes to be processed polymorphically .

Defining Interface

An interface is just defined like a class but a keyword interface is used instead of the keyword class. It can contain either constants (final fields) or abstract method declarations or both. All the methods in an interface are public and abstract by default and all the fields are public, static and final by default. Its syntax is .

[public] interface InterfaceName {

// constant variable declarations

// abstract method declarations

}
The optional public access specifier specifies whether this interface can be used by other classes and packages or not. If public access specifier is omitted, only the classes within its package can use the interface. The keyword interface indicates that an interface named InterfaceName is being defined. The rules for naming the interface are the same as that of valid
Java identifiers. For example, in order to define the Shape interface, we write

interface Shape {

   double area();

   double circumference();

}

How to Implement an Interface

As interface provides nothing but abstract method declarations so you will have to implement those methods in your own classes. To do so, include the implements keyword as part of class definition followed by the name ofthe interface that you want to implement and implement all of the methods in the interface with the same signature specified in the interface declaration. If a class does not implement all of the method of the interface, the class must declare itself as abstract. When a class implements an interface you can think of the class as signing a contract with the compiler agreeing to implement all the methods specified by the interface or will declare itself abstract. The simplified form for implementing an interface by a class is

[accessspecifier] [modifier] class ClassName

implements InterfaceName {

       // provide implementation for method in interfaces

}

Here, access specifier (such as public, private, protected) and modifier (such as static) are the same as discussed previously. The ClassName is the name of the class. It is followed by implements keyword which is followed by name of the interface, InterfaceName.
This name identifies the name of interface whose methods are to be implemented. The body of this class contains definitions of all the methods contained in the interface.

Now let us consider an example of the Rectangle class that implements the Shape interclass

Rectangle implements Shape {

        privatedouble length ,breadth;

        public Rectangle(double l,double b){

              length == l; breadth == b;

        }

}

publicdouble area(){return length*breadth;}

publicdouble circumference(){return2*(length+breadth);}

Note that the methods area() and circumference() declared in the interface Shape are defined public in the class Rectangle in which they are implemented. If you omit the keyword public from any of these methods, the code will not compile. This is because the implementation of interface's method must not have an access specifier that is more restrictive than implicit in the abstract method declaration and you cannot get less restrictive than public.

How to Creating interface Reference

Once you have defined and implemented an interface, its now time to know how variable of interface type can call the methods of the classes that implement it polymorphically.
It is not possible to create an instance of interface, as they do not provide an implementation for any methods that they declare, so to instantiate them will be completely illogical. However, you can create an object of a class that implements an interface and assign it to interface reference variable. If you assign an object to the interface reference variable that does not implement that interface, the compiler will generate an error message.

For example, The statements

Shape s = new Rectangle (10,20) ;

System.out.println("Area of Rectangle == " + s.area());
The first statement creates an Rectangle object which is assigned to the reference variable s of Shape type. The second statement will print the area.
The complete java interface example

//use of interfaces

interface Shape {

         double area(); // area method declaration

         double circumference(); // circumference method declaration

         class Rectangle implements Shape {

                private double length,breadth; // Instance data

                public Rectangle(double l, double b) {

                    length = l; breadth = b;

                }

                public double area() { return length*breadth;} //Implementations of abstract methods     

                public double circumference () { return 2* (length+breadth) ;}

           }

        class Circle implements Shape {

             public static final double PI = 3.142;

             private double radius ;

             public Circle(double r) { radius = r; }

             public double area() { return PI*radius*radius; } //Implementations of abstract metheods.          

             public double circumference() { return 2*PI*radius; }

      }

}

class InterfaceDemo {

      public static void main (String[] args) {

            Shape[] s = new Shape[2]; //Create an array to hold shapes

            s[0] = new Rectangle(10,20); //Assign rectangle object

            s[1] = new Circle(3); //assign circle object

           double total_area = 0;

           for(int i = 0; i< s.length; i++) {

                System.out.println("Area =" +s[i].area()); // Compute area of shapes

                //Compute circumference of shapes

                System.out.println("Circumference =" +s[i].circumference()) ;

            }

       }

}





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.