I've been programming in Java for a while, but mainly just small command line programs. Now I've got an ever-so-slightly larger project, and I'm trying to work out a decent design.
It's a small database lookup/update tool.
I have three different types of tables, but there are several shared columns between the tables.
EG:
Table1 (FieldName, FieldId, FieldValue, AppName, AppId, AppValue)
Table2 (FieldName, FieldId, FieldValue, UpdatedBy)
Table3 (FieldName, FieldId, FieldValue, UpdatedDate)
I want to have something like this:
abstract class BaseTable {
FieldName
FieldId
FieldValue
}
class Table1 extends?implements? BaseTable {
FieldName
FieldId
FieldValue
AppName
AppId
AppValue
}
class Table2 extends?implements? BaseTable {
FieldName
FieldId
FieldValue
UpdatedBy
}
class Table3 extends?implements? BaseTable {
FieldName
FieldId
FieldValue
UpdatedDate
}
I'll read arguments to determine which type of table I need, but basically I want to do something like this:
BaseTable bt = null;
if (tableType = Table1)
bt = new Table1();
else if (tableType = Table2)
bt = new Table2();
else if (tableType = Table3)
bt = new Table3();
bt.doSpecificStuff();
HashMap<String,BaseTable> map = new HashMap<String,Table1>();
map.put(someString, bt);
There are a couple of problems here:
I can't access the subclass' extra fields using this design.
I don't want to use
Table1 t1 = new Table1();
, because then I can't use common methods because of the different parameter types.When I try to create the hashmap to hold instances of the objects, I get a compile error saying:
Type mismatch: cannot convert from HashMap<String,Table1> to HashMap<String,BaseTable>
So basically, there appear to be several problems with my design, and I can't think of an approach that solves these issues. I don't want to create three unrelated classes, because I feel that it defeats the purpose of OOO, and that my program warrants its use. Besides, this must be a common problem with a simple and elegant solution, but I haven't been able to find much that explicitly deals with an object having extra fields in its subclasses. Can anyone suggest a better design for my program, that somehow allows me to access the subclass fields while being able to instantiate with the base class object type?