Cao Felix Cao Felix - 3 months ago 12
Java Question

Java implements different methods in two classes using one interface

I have a Java question and I can't see how I can implement the methods correctly. I am not very good with architecture.

Data Manager interface class:

public interface DataManager {
public void readData();
public void writeData();
}


Data abstract class:

public abstract class Data implements DataManager {
@Override
public void readData() {};
@Override
public void writeData() {};
}


Data Reader class:

public class DataReader extends Data {
// I want to implement the readData() here
}


Data Writer class:

public class DataWriter extends Data {
// I want to implement the writeData() here
}


If I want to implement the readData() and writeData() separately in two different classes with only one interface, is it possible? I don't know why I am doing this way. Maybe it just looks cleaner and easier when I add more methods to the reader or writer class. Should I implement everything in just one single class?

I want this library to allow users using the manager object to have access for data reading and writing. But for implementation, I don't know how I can do it correctly.

Answer

After a lot of modification, so I do it this way and I think it fits my solution.

Data Manager interface class:

public interface DataManager {
   public Data readData(); // from database
   public void writeData(); // to database
}

DataConnector class:

public class DataConnector implements DataManager {
   DataCreate creator = new DataCreate();
   @Override
   public Data readData() {
       return creator.readData();
   };
   @Override
   public void writeData() {
       creator.writeData();
   };
   public Connection getConnection() {...};
   public void close() {...};
}

Data Create class:

public class DataCreate {
   public void readData() {
      new DataReader().readData();
   }

   public void writeData() {
      new DataWriter().writeData();
   }
}

Data Reader class:

public class DataReader {
   // I want to implement the readData() here
   public Data readData(){...};
}

Data Writer class:

public class DataWriter {
   // I want to implement the writeData() here
   public void writeData(){...};
}

Example:

DataManager manager = new DataConnector();
manager.readData();
manager.writeData();

So clients will only use methods from the manager public interfaces to do database reading and writing. Edward Peters mentioned composition to me and I did not understand it at that time. I am not very sure if what I am doing now is what composition should be doing. I think the credit should go to him. Thanks for the help.