Definition

Interface in java is a mechanism to achieve abstraction.

What is Abstraction ?

Process of Hiding internal details and functionality is known as abstraction.

Abstraction can be achieved in Java Using Abstract Class & Interface concept.

How do you achieve Abstraction using interface ?

Java allows only abstract methods inside the interface. Abstract method is nothing but method definition with out implementation.

interface ICalculator {
      int  add ( int data1, int data2 );
}

Can we instantiate interface ?

No. Since interface contains abstract methods, you cannot instantiate

How do you achieve implementation for interface ?

Java allows implements keyword for the class to implement any interface.
Implemented method should be annotated by @Override.
class Calculator implements ICalculator {
    // Implemented Method of ICalculator  
     @Override
     int add ( int data1, int data2 ) {
         return data1 + data2;
     }
}

How do you achieve loose coupling in Interface ?

Use interface as object reference and assign the object of implemented class.
Concept of referencing is known as Child reference to parent object.
ICalculator calculatorReference = new Calculator ();

Should implemented class have abstract method implementation only ?

No. implemented class can have own methods.
class Calculator implements ICalculator {
     // Implemented Method of ICalculator
     @Override 
      int add ( int data1, int data2 ) {
         return data1 + data2;
      }
     
      // Own Method for Calculator
      int diff ( int data1, int data2 ) {
         return data1 - data2;
      }
}

Can Child Reference can access all the methods present in implemented class ?

No.
 Here, In the declaration,
  ICalculator calculatorReference = new Calculator ();
 
 calculatorReference can access only add ( int data1, int data2 )
 and not the diff ( int data1, int data2 )

NOTE: Only implemented class reference can access own method of implemented class

That is,

Calculator calculator = new Calculator ();

Here reference of calculator can access both

add ( int data1, int data2 ) & diff ( int data1, int data2 )

Summarizing access levels,

  • Child reference or interface class reference (here calculatorReference ) can access only the implementation of abstract class.
  • Parent reference or implemented class reference (here calculator ) can access both implemented and own methods in the class.

Next topic: Components of interface in Java

Advertisements