Java Interfaces
Interfaces are used so that any object that implements it, will use certain method signatures. Consider the following classes: Person, Employee, and Customer. Persisting a Person, Employee, and Customer object will always involve connecting to a data store. However, the implementation for persisting a Person, Employee and Customer may differ. If we were to persist these objects into a relational database, such as MySQL, the SQL syntax would more than likely be different because each object may have different attributes.
Unlike Abstract Classes, Interfaces contain only method signatures. Also, a class can implement multiple interfaces. Whereas, only a single Abstract class can be inherited.
IDataHandler
public interface IDataHandler
{
//Create, Read, Update, Delete
public void insert(Object obj);
public Object select(int id);
public void update(Object obj);
public void delete(Object obj);
}
PersonDAO
public class PersonDAO implements IDataHandler
{
//Database Connection fields
public PersonDAO() {
//Initialize the DB fields here...
}
public void insert(Object obj) {
Person person = (Person)obj;
System.out.println("Inserting " + person.name + " into the database.");
}
public Object select(int id) {
System.out.println("Selecting " + id + " from the database.");
Person person = new Person();
return person;
}
public void update(Object obj){
Person person = (Person)obj;
System.out.println("Updating " + person.name + " from the database.");
}
public void delete(Object obj) {
Person person = (Person)obj;
System.out.println("Deleting " + person.name + " from the database.");
}
}
Person
public class Person
{
public String name;
public int age;
public Person() {
this.name = "John Doe";
this.age = 0;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Driver
public class Driver
{
public static void main(String[] args) {
PersonDAO dao = new PersonDAO();
Person rob = new Person("Rob", 22);
Person jess = new Person("Jess", 20);
dao.insert(rob);
dao.insert(jess);
//Make changes to jess
dao.update(jess);
dao.delete(rob);
}
}



ArianaLips - May 13th, 2009 @ 1:46pm reply