by Dinesh Thakur Category: Introduction to Java

Java interface used for achieving 100% abstraction because of the interface only contains methods without any implementation or body. However, it contains only abstract methods and constants (final fields). Any field that declared inside interface is public, static, and final by default, any method is an abstract public method. 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 .

Interfaces are like class templates; we never build them to represent any object,  only to run interference between OOP concepts and Java programs.  

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 Interface Name 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();

}

Interface Explanation  

In much the same way that abstraction does, interface hides the intricate details of implementation and shows only the necessary functionality, but there is a big difference between them. The methods declared in the interface are all abstract while, in abstraction, you can have a combination of abstract and non-abstract.

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 of the 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 {

        private double length ,breadth;

        public Rectangle(double l,double b){

              length == l; breadth == b;

        }

}

public double area(){ return length * breadth;}

public double circumference(){return 2 * (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 (){return2*(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());

            }

       }

}

Extending an Interface

As I mentioned earlier, one interface can extend another but remember that an  interface can’t implement any other interface; that can only be done by a class.  The next example shows this extension in operation. We are using two interfaces –  StaffNoDetails and EmployeeDetails which will extend the StaffNoDetails class.  First, we create the StaffNoDetails interface and give it one method called staffNo.

publicinterface StaffNoDetails {

  void staffNo();

}

Next we create a further interface called EmployeeDetails. This will extend the  StaffNoDetails and will have a name() method declared in it. Because the extends  keyword has been used, the StaffNoDetails methods may now be inherited by EmployeeDetails; the latter interface will now have two methods – name() and  staffNo().

publicinterface EmployeeDetails extends StaffNoDetails {

    void name();

}

A class called Details is created next and this will implement EmployeeDetails.  We  must give both methods, name() and staffNo() a body because the StaffNoDetails  interface methods were inherited by the EmployeeDetails method.  
Details is also going to be the main class:

publicclass Details implements EmployeeDetails{

    public void name(){

       System.out.println("Dinesh Thakur");

    }

    public void staffNo(){

       System.out.println("0001");

    }

    public static void main(String[] args{

        Details details =new Details();

        System.out.print("Name: ");

        details.name();

        System.out.print("Roll No: ");

        details.staffNo();

     }

}

The output of this will be:

Name: Dinesh Thakur

Roll No: 0001

Interface vs. Class

There are a few differences between interfaces and classes:  
• An interface cannot instantiate whereas a class can. 
• Every object that creates in an interface after implementation has  identical states; in a class, every object has a state of its own. 
• In an interface objects must implement the defined contract to define their behavior; in a class, unless an object overridden, all objects have the same behaviors.  
• Interface variables are static public finals and, when defined, must have a  value assigned. With a class, the variables are instance unless specified otherwise.  
• Interfaces cannot inherit classes, but they can extend multiple interfaces.  Classes can inherit only a single class and can implement multiple interfaces.  
• Interface methods are public abstract and have no definition; in a class,  every method must define unless the abstract keyword has used as a decorator.  





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.