March 23, 2016

Interface in java

Java Interface with example code

      A Java interface is similar like class, where contains only unimplemented methods. The class which implements that interface should define that method. This way the java achieve polymorphism. In other words, java doesn't support multiple inheritance directly but can be achieved it indirectly through Interface concept.



package interfaces;
public class Main {

   
         
    public static void main(String[] args) {
     
          shape circleshape=new circle();
       
             circleshape.Draw();
           
             shape trish=new triangle();
             trish.Draw();
           
    }
}

 interface shape
 {
     public   String baseclass="shape";
   
     public void Draw();
   
   
 }
 class circle implements shape
 {

    public void Draw() {
        System.out.println("Drawing Circle here");
    }
 
 
   
 }

An interface is a group of methods with empty bodies ( nothing will be defined in that methods), Here shape is an Interface that contains method Draw(), which is an unimplemented method

package interfaces;

public class triangle implements shape {

@Override
public void Draw() {
// TODO Auto-generated method stub
System.out.println(" ni");

}

}

What will happens if two a class implements two interfaces having a similar method in both?

I called the function System.out.println(new InterfaceTest().hello());

we dont know which interface is working

package com.tutorial.interfaces;
/**
 *
 */

/**
 * @author belazy
 *
 */
public class InterfaceTest implements InterfaceOne, InterfaceTwo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//new InterfaceTest();
System.out.println(new InterfaceTest().hello());

}

@Override
public String hello() {
// TODO Auto-generated method stub
return "test";
}

}


+Belazy L


http://javabelazy.blogspot.in/

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments