Friday, June 10, 2011

trick to obtain object of type interface in java

this concept makes java so scalable and newer vesions of JDK [java development kit] are incorporated with new functionality without messing with the previous packages and classes using this.

in fact this is one of the key concepts upon which the JDK is built.in recommends use of Interfaces on to of hierachy.Thus:
Interfaces -----> implementing classes------> sub-classes


To understand this concept lets take an example :-
in JDBC [java database connectivity] we write the following line of code to create a connection:

Connection con = DriverManager.getConnection( "jdbcurl", "username" , "password") ;

from the above code it can be well understood that ' DriverManager ' is a class which has a static method getConnection() [which takes 3 arguments] and returns an object of type Connection.But ' Connection ' is an interface in java.So how can it ever have an object ?
Problem :- Interfaces cant have objects since they contain atleast one abstract method. So how does ' Connection ' Interface have an object [i.e. ' con ' here] ?

Solution[Concept behind] :-
we know once we have the appropriate object, then using any method is not a problem.But how to obtain object of Interface, coz dats not possible. Thus to obtain objects of type Interface the following trick is deployed

interface Interface
{
public void mymethod(); //abstract method without body
}
class B implements Interface
{
public void mymethod() //giving body to the method
{
System.out.println("Hello Geeks");
}
}

class A
{
public Interface mymethod2() //notice the return type of this method
{
Interface itr=new B(); //here is the juice of the program
//itr is an object of type Interface with content of class B
return itr;
}
}
public class InterfaceProject
{
public static void main(String[] args)
{
A aobj=new A();
Interface interface_obj=aobj.mymethod2(); //thus creating object of type interface
interface_obj.mymethod();
//finally mymethod() is called with interface_obj
}
}


similar trick is found in jdk at various instances: for example ' Servlet ' is an interface having certain concrete and certain abstract methods. this interface is implemented by classes like HttpServlet class and GenericServlet class.These classes give their own implementation to the methods defined abstract in the ' Servlet ' interface.

one should also understand that interface-object and object of type interface are not the same things.the former is not possible while the later is.

No comments:

Post a Comment