Tuesday 6 October 2015

What is Interface in java with example

Interface is a mechanism to achieve fully abstraction. It's look looks like as class but not a class. It solve is with a powerful construct called interface.



It can be used to fully abstraction, generic template and multiple inheritance in java. It a blueprint of a class.











For Example:




/**
 *
 * @author pradeep
 */

interface interfaceprint
{  
void printinterface();  
}  
  
class intr implements interfaceprint
{  
public void printinterface()
{
    System.out.println("Hello i am interface");
}  
  
public static void main(String args[])
{  
intr obj = new intr();  
obj.printinterface();  
 }  



Result: Output of this program is 

run:
Hello i am interface

BUILD SUCCESSFUL (total time: 1 second)








Multiple Inheritance in java

Multiple inheritance in java if a class implements multiple interface or extends multiple interface that's is called multiple interface.


For Example:


/**
 *
 * @author pradeep
 */
interface Multiinterfaceprint
{  
void printmultiinterface();  
}  
  
interface Multiinterfaceshow
{  
void showmultiinterface();  
}  
  
class multiintr implements Multiinterfaceprint,Multiinterfaceshow
{  
  
public void printmultiinterface(){System.out.println("Hello i m interface");
}  
public void showmultiinterface()
{
System.out.println("Welcome to my city");
}  
  
public static void main(String args[])
{  
multiintr obj = new multiintr();  
               obj.printmultiinterface();  
               obj.showmultiinterface();  
 }  




Result: Output  of this program is  


run:
Hello i m interface
Welcome to my city

BUILD SUCCESSFUL (total time: 0 seconds)




Advantage of interface:


  1. Without bothering about implementation; we can achieve the security of implementation.
  2. Multiple interface can't be allow, however by using interface you can achieve the same.
  3. Interface are mainly used to provide polymorphic behavior.


Disadvantage of interface:

  1. Interface are slower and more limited than other ones.
  2. Interface should be used multiple number of times otherwise it hardly any use of having them.





No comments:

Post a Comment