Java interface use for achieving 100% abstraction because the interface only contains methods without any implementation or body. However, it has only abstract methods and constants (final fields). Any field declared inside the interface is public, static, and final by default, and any method is an abstract public method. It specifies what must do but not how. Once an interface is defined, the class implements an interface by implementing each method declared by the interface. Also, one class can implement any number of interfaces.
We’ll be covering the following topics in this tutorial:
Advantages of Interface
• Interfaces are easier to work with than inheritance because you do not have to worry about providing any implementation details in 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 in Java defines as a class, but a keyword interface is used instead of the keyword class. It can contain either constant (final fields) or abstract method declarations or both. All the interface methods 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 other classes and packages can use this interface or not. If the public access specifier omits, only the classes within its package can use the interface. The keyword interface indicates that an interface named Interface Name is defined. The rules for naming the interface are the same as that of valid Java identifiers. For example, 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 classes. 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 interface methods, 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 interface methods 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 specifiers (such as public, private, protected) and modifiers (such as static) are the same as discussed previously. ClassName is the name of the class. It follows by the implements keyword, followed by the name of the interface, InterfaceName.
This name identifies the name of the interface whose methods are to implement. The body of this class contains definitions of all the methods included 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 implement. If you omit the keyword public from any of these methods, the code will not compile. The implementation of the 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 the public.
How to Creating interface Reference
Once you have defined and implemented an interface, it’s now time to know how the variable of an interface type can call the classes’ methods that implement it polymorphically.
It is impossible to create an instance of an 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 an 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 a Rectangle object 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;} 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;} 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 circumference of shapes System.out.println("Circumference ="+s[i].circumference()); } } }
Implementing Multiple Interface
A class can implement more than one interface. For this, you write all interfaces that the class implements separated by commas following the implements keyword. The class body must provide implementations for all of the methods specified in the interfaces. The syntax for implementing multiple interfaces is
[publicl class className [ extends superClassName] implements interface1, interface2, interfaceN { // Provide implementation for methods of // all included interfaces // .................... }
In order to understand this let us consider a program.
// use of Multiple interfaces // Interface one interface Interface1 { void f1() ; } //Interface two interface Interface2 { void f2(); } class X implements Interface1,Interface2 { // definition of method declared in interface1 public void f1() { System.out.println("Contents of method f1() in Interface1"); } // definition of method declared in interface2 public void f2() { System.out.println("Contents of method f2() in Interface2"); } public void f3() { System.out.println("Contents of method f3() of class X"); } } class Main { public static void main(String[] args) { Interface1 v1; //Reference variable of Interface1 v1 = new X (); //assign object of class X v1.f1(); Interface2 v2; //Reference variable of Interface2 v2 = new X(); //assign object of class X v2.f2(); X x1=new X(); x1.f3(); } }
Output :
Contents of method f1() in Interface1
Contents of method f2() in Interface2
Contents of method f3() of class X
Explanation: In this program, two interfaces named Interface1 and Interface2, are defined. Interface1 contains method declaration of method f1(), and Interface2 contains method declaration of method f2(). Class x implements both these interfaces. So it provides the definitions of f1() and f2(). Besides, it also defines its method f3().
Extending an Interface in Java
As I mentioned earlier, one interface can extend another but remember that an interface can’t implement any other interface; a class can only do that. 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.
public interface StaffNoDetails { void staffNo(); }
Next, we create a different interface called EmployeeDetails. It 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().
public interface 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 are also going to be the main class:
public class 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 created 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 is 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 been used as a decorator.
Interface Vs. Abstract Classes
Interfaces and abstract classes both implement polymorphic behavior and seem to be similar, but they are different in the following ways:
1. An interface is purely abstract, i.e., methods in an interface only have declarations no implementations. On the other hand, abstract class methods may or may not have an implementation.
2. A class implementing an interface must implement all of the methods declared in the interface. A class extending an abstract class needs not to implement any of the abstract class methods.
3. Abstract classes are used when there is an IS-A relationship between the classes. However, interfaces can be implemented by unrelated classes.
4. You can implement more that one interface, but you cannot extend more than one abstract class,
5. User-defined exceptions can be defined within an interface itself, which is not the case with the abstract class.
6. Members of an abstract class may have any access specifier modifier, but members of an interface are public by default and cannot have any other access specifier.
7. Abstract class definition begins with the keyword abstract followed by the class definition. On the other hand, the interface definition begins with a keyword interface.
8. All variables in an interface are public, static, and final by default, whereas an abstract class can have instance variables.
9. Abstract class does not support multiple inheritance, whereas the interface supports multiple inheritance.
10. If you define an interface and then later add a new method to an interface, you must implement that method in all of the classes that implement it. However, in an abstract class, you can safely add non-abstract methods to that class without requiring any modification to existing classes that extend the abstract class.
11. Interface is slow compared to the abstract class as they find the actual method in the corresponding classes.
12. Interface can extend another interface, whereas an abstract class can extend another class and implement multiple interfaces.
13. An abstract class can have constructors, but the interface cannot have constructors.