Interface Concept Simplified In Java



An interface is like a simple java class that has static constants and abstract methods.Java uses interface to implement multiple inheritance.A java class can implement multiple java interfaces.All methods in an interface are public and abstract. So an interface is a pure abstract class.When a child class needs to be created from two or more number of super classes,the phenomenon is called multiple inheritance. Java does not support multiple inheritance directly(meaning java classes can not have more than one super class like Class A extends B extends C {} is illegal in java) but with interface we can do similar approach.In real life we can create several distinct classes to support multiple inheritance.In java interface is a reserved keyword that implies an interface consists of a set of instance method interfaces without any implementation.A class can implement an interface by providing an implementation for each of the methods specified by the interface.The class which is trying to implement the method must state to java virtual machine that this class is going to implement some interface by the keyword "implements".Like class circle implements Drawable{....}. Even though the interfaces are not exact classes,they can be compared to abstract classes in the sense that we can not create objects from interface or abstract class but can be used as a base for making sub classes.So Interface allows the creator of the classes to establish the form of the classes,method names,argument lists and return types but no bodies.It is possible to add initialized definitions for primitives but these becomes compile time constant.They are static and final thus no storage to be created for the actual object.

An interface says "this is what all classes that implement this particular interface shall look like.Any code that  uses a particular interface knows what methods may be called for the interface.So interface is used to establishes a protocol between classes. Creating an interface -instead of class,we need to use the word called Interface.It can be public or friendly."
For primitive types,they become compile time constant which is equivalent to create enum in java.We can create an interface containing all over enumeration identifier providing an unique integer value. This is not ideal.
Syntax of interface:

interface interfaceName{
//variables and methods
}
//another one
interface interfaceName[extends Name1]{
//variables and methods
}
 
Class structure implementing interface:

class MyClass extends SuperClass implements interface1,interface2,interface3......intefaceN{
//body of the class
}
 
The member variables present in an interface should be static and final.
Example:

interface Pet{
public void test();
}
public class Cat implements Pet{
public void test()
{
System.out.println("Interface method implemented in the child class");
}
public static void main(String args[])
{
Pet p=new Cat();
p.test();
}
}
 
output of the code:
$javac Cat.java
$java -Xmx128M -Xms16M Cat
Interface method implemented in the child class
One more example:

interface Area{
    final static float PI=3.14F;
    float compute(float x,float y);
}
class Rectangle implements Area{
    public float compute(float x,float y)
    {
        return x*y;
    }
}
class Circle implements Area{
    public float compute(float x,float y)
    {
        return PI*x*y;
    }
}
public class MYInterfaceTest{
    public static void main(String args[])
    {
        Rectangle rect=new Rectangle();
        Circle cir=new Circle();
        Area area;
        area=rect;
        System.out.println("Area of the rectangle "+area.compute(10,20));
        area=cir;
        System.out.println("Area of the rectangle "+area.compute(10,20));
    }
}
 
The output of the code:
$javac MYInterfaceTest.java
$java -Xmx128M -Xms16M MYInterfaceTest
Area of the rectangle 200.0
Area of the rectangle 628.0
A more real time example:
Assume that there are two classes for an organization

  • One PermanentEmployee
  • One Vendor Employee
Now each class has their unique components called Qualification,MainCompany,Current_Project,Current_Project,Experience(),Next_Project().
class PermanentEmployee class VendorEmployee
Qualification MainCompany
Current Project CurrentProject
Experience() Next_Project()
Class Organization
......
Resume
Now if the Organization wants to have a resume for both type of Employees.So the Organization class with define an interface called Resume.

interface Resume{
....
void EmpResume();
}
class  PermanentEmployee Extends Employee implements Resume{
Qualification;//member variables
Current_Project;//member variables
Experience(){};//member function
public void EmpResume()
{
....
//code to implement the resume
}
}
class VendorEmployee implements Resume{
MainCompany;//member variables
Current_Project;//member variables
Next_Project(){}//member function
public void EmpResume()
{
....
//code to implement the resume
}
}
//so the implementation of the code goes like
PermanentEmployee pe=new PermanentEmployee();
pe.EmpResume();
VendorEmployee ve=new VendorEmployee();
ve.EmpResume();

//Futher more we can implement an array of Resume. This is possible as both implement Resume hence they become same type.
Resume listOfResume=new Resume[10];
listOfResume[0]=new PermanentEmployee;
listOfResume[0]=new VendorEmployee;
....
.....

 
Interface methods
Interface methods are those methods which are abstract methods appearing in the interface.If a class implements an interface but does not implement one or more of the interface methods,the whole class becomes an abstract class and can not be instantiated.The interface of a method consists of the name of the method,it returns type and number and types of its parameters.All methods present in an interface are public by default.This means when we implement an interface,we need to define the methods.This is the reason why we need to define them as public.Otherwise a default or friendly will restrict the accessibility of the method during inheritance.(not allowed in java).

interface MyInterface{
public abstractvoid function1();
public abstractvoid function2();
}
class class1 implements MyInterface{
public void function1(){
...
...
}
}
class class2 extends class1{
public void function2(){
...
...
}
}

 
The interface contains two methods function1() and function2().class1 implements the interface but does not contain the function2() which is a part of the interface.This means that class1 becomes an abstract class.It can not be instantiated.However once we create a subclass class2 of class1 and define function2().That means class2 has successfully implemented all methods of interface-MyInterface.So class2 can be instantiated.
When to use interface and when to use abstract class?
We need to use abstract class when a template needs to be defined for a group of sub classes. But we need to use interface when a role needs to be defined for other classes regardless of the inheritance tree of these classes.
The class can not implement two interfaces in java that have methods with same name but different return type.
Difference between class and Interface:
Sl No Class Interface
1 we can instantiate variables and create an object from it We can not instantiate variable and create object from it.
2 class contains concrete methods Interface can not contain any concrete methods
3 Access Specifiers can be public,protected,private Only specifier is public
How interface can share member variables:
Interface can be used to declare a set of constants that can be used in different classes.Since such interfaces do not contain methods.we do not need to implement any methods.The variables treated as constant will be available to any class that implements the interface.The values can be used in any methods,part of any variable deceleration or anywhere.
interface Response{
static final int yes=1;
static final int No=2;
    
}
class Enquire implements Response{
public int ask(){
    System.out.println("Have you seen google -Type your response: yes-1 No-2");
    int type=0;
    try{
    type=System.in.read();
    }
    catch(Exception e){}
    return type;
}
}
public class MyServey implements Response{
    public static void main(String args[])
    {
        Enquire myResp=new Enquire(); 
        reply(myResp.ask());
        reply(myResp.ask());
    } 
    static void reply(int type)
    {
        switch(type){
        case yes:
            System.out.println("You have seen google.Thanks!");
            break;
        case No:
            System.out.println("You have not seen google.Thanks!");
            break;
        default:
            System.out.println("You have given a valid input!");
        }  
    }
    
}
 
How inheritance can be seen in interface:
Classes can have multiple interface implemented.Similarly interfaces also have a chain of inheritance that is an interface can be derived from another interface.

import java.awt.Graphics;
interface BoxDimention{
int top;
int bottom;
int left;
int right;
}
interface DrawBox extends BoxDimention{
void draw(int a,int b,int c,int d);
}
class Box implements BoxDimention{
public void Area(){
....
//code
}
}
class ShowBox implements BrawBox{
int x,y,z,w;
void draw(int a,int b,int c,int d){
x=a;
y=b;
z=c;
w=d;
void paint(Graphics g){
g.drawRect(x,y,z,w);
}
}
}
 
The Box just needs access to the constants and would implement BoxDimension while the class ShowBox needs access to the draw() method and would implement DrawBox.
Multiple inheritance through interface
Multiple inheritance is allowed for interfaces.if we need to do both,to ensure the box as well as draw the box then-

import java.awt.Graphics;
interface BoxDimention{
int top;
int bottom;
int left;
int right;
}
interface DrawBox{
void draw(int a,int b,int c,int d);
}
interface Box extends BoxDimention,DrawBox{
void area();
}
class ShowBox implements Box{
//code for area
//code for draw
}
 
Variable type is given by interface
We can declare a variable whose type is given by the interface.If Drawable is an interface and if Line and Circle class that implement Drawable then we can say:

Drawable figure;//declare a variable of type interface-Drawable.It can refer to any object 
//that implement Drawable interface.
figure=new Line();// figure refers to Line object
figure.draw(g);//calls the draw() method of class Line
figure=new Circle();// figure refers to Circle object
figure.draw(g);//calls the draw() method of class Circle
 
type can be used to declare variables.A type can also be used to specify the type of a parameter in a subroutine or the return type of a function.In java a type can be either a class,an interface or a primitive types.
Things to remember in interface:
  • Java classes can implement multiple java interfaces. 
  • All variables declared in interface are constants.
  • Interface methods must ends with a semicolon(;).
  • It is necessary to implement all the methods declared in the interface.
  • Classes also should override all methods declared in the interface.
  • The interface allows sending message to an object without concerning which class it belongs.
  • Class needs to provide functionality for the methods declared in the interface.
  • All methods in an interface are implicitly public and abstract.
  • An interface can not be instantiated.
  • An interface reference can point to objects of its implementing classes.
  • An interface can extend to one or many interfaces.
  • A class can extend to one class but implement any number of interfaces.
  • An interface can not implement another interface.It has to extend another interface if needed.
  • An interface which is declared inside another interface is called as nested interface.
  • At the time of declaration,interfaces variables must be initialized. Otherwise compiler will throw an error message. 
  • Any object created from the concrete class will also have the interface method.
  • While interface are allowed to extend to other interfaces,if sub interfaces can not define method of super interface,the sub interface is still be an interface.
  • An interface can not extend to a class.This would violate the rule of an interface(Interface can have only abstract methods and constants).
Interface Concept Simplified In Java Interface Concept Simplified In Java Reviewed by Animesh Chatterjee on October 15, 2018 Rating: 5

No comments:

Powered by Blogger.