Pages

Saturday, July 28, 2012

Adapter Class

In this article you will learn about adapter classes their use and how to write adapter classes manually.
Before going for adapter classes you need to have an idea about Abstract classes and Interfaces.

as we know if we declare an interface all its methods must be abstract and need to be override in the sub class which implements that interface.
>> So whats the problem here ? 
Its very time consuming and difficult task to provide definitions for each and every method of interface in the sub-classes.
>> what is the need of adapter classes ?
If you are not interested to override all the methods of interface you can make use of adapter classes.

Adapter class: it is an abstract class implementing any interface and it contains definitions of some of the methods of the interface it is implementing.this Adapter class can be inherited now by any class without any bounds of  overriding  all the methods of the interface because the adapter class contains the definitions of that methods.
Note: if a method isn't overridden  in the adapter class then it is necessary to be overridden it in the sub class otherwise compiler will give an error.

here is an example showing adapter class :

import java.io.*;
import java.util.*;
interface iface  
{
public void input(int x,int y);
public void biggest();
public void display();
}

abstract class adapter implements iface
{
int d,e;
public void input(int x,int y)
{
d=x;
e=y;
}
}
class big extends adapter
{
int c;
public void biggest()
{
if(d>e)
{
c=d;
}
else
{
c=e;
}
}
public void display()
{
System.out.println("biggest number is :"+c);
}

}
public class main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
big a=new big();
int g=sc.nextInt();
int h=sc.nextInt();
a.input(g,h);
a.biggest();
a.display();
}
}

In the above example the input() method is optional to override in the subclass because it is already overridden in the adapter class.
This example is just my attempt to make the concept clear,you may not find adapter classes much useful here in this example but in real time where interfaces contains tens of methods the programmers never like to override all of them directly in their classes so they use adapter classes and its a very effective technique.
It reduces code and saves time.

No comments:

Post a Comment