Wednesday, December 1, 2010

Interfaces with methods in Java



Java Interfaces are not allowed to have Methods. However they are allowed to have variables and Constants(final).

Using this, we can have methods in Java Interfaces. Here is how :-

1)
Develop a class with a method

Programmer.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package methodsininterfaces;

import java.lang.reflect.Method;

/**
 *
 * @author Champak
 * Varanasi,India
 * Mob 91-9335874326
 */
public class Programmer  {
public static String getProgrammer(String programmer)
{
//The Method to be accessed via the Interface
   programmer=programmer.trim().toLowerCase();
if(programmer.equals("champak"))
    return "Champak Roy";

return "Unknown";
}


public static Method returnMethod()
{
//Return the Method
try
{
return Programmer.class.getMethod("getProgrammer",String.class);
}
catch(Exception ex)
{
System.out.println(ex);
return null;
}
}
}


The Interface  ProgrammerInterface.java

ProgrammerInterface.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package methodsininterfaces;

import java.lang.reflect.Method;

/**
 *
 * @author Champak
 * Varanasi,India
 * Mob 91-9335874326
 */
public interface ProgrammerInterface {
public static Method interfaceMethod=Programmer.returnMethod();
//The Method has been stored in the interface
}


Calling the Interface Method

Main.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package methodsininterfaces;

import java.util.Scanner;



/**
 *
 * @author Champak
 * Varanasi,India
 * Mob 91-9335874326
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)throws Exception {
Scanner sc=new Scanner(System.in);
        System.out.print("Enter the name of the Programmer = ");
        String martyr=sc.nextLine();
        System.out.println(Programmer.interfaceMethod.invoke(null, programmer));
//In the invoke method pass null for a static method, or else pass the object to which the method belongs
    }

}


The Output

run:
Enter the name of the Programmer = champak
Champak Roy
BUILD SUCCESSFUL (total time: 13 seconds)

No comments:

Post a Comment