Reputation: 451
I'm trying to implement a small MongoDB application as a jar file which can be used from a series of other applications. (Running Java 6)
The purpose is to have a class that handles and contains DBCollection
, MongoDatabase
and MongoClient
.
This superclass can be extended by these other applications and the MongoDB used from these. I would also like the other applications to implement an interface which contains 1 insertIntoDB()
method. This insertIntoDB()
method should take 1 parameter which would be another subclass and herein is my problem. How can the interface specify an extension of a generic type so that each implementation returns the extended types ?
Below is a bit further explanation:
class AsuperClass implements Ainterface {
MongoClient aMongoClient
MongoDatabase aMongoDatabase
initMongoDb() {
//doStuff
}
}
class AsuperPojo {
int propA
String propB
}
interface Ainterface {
void insertToDb(AsuperPojo);
}
class SubClass1 implements Ainterface extends AsuperClass{
@Override
public void insertToDb(SpecialSubClass1Pojo aSpecialSubClass1Pojo) {
//doStuff
}
}
class SpecialSubClass1Pojo() {
int propA
String propB
}
class SubClass2 implements Ainterface extends AsuperClass{
@Override
public void insertToDb(SpecialSubClass2Pojo aSpecialSubClass2Pojo) {
//doStuff
}
}
class SpecialSubClass2Pojo() {
int propA
String propB
}
Maybe there's a completely different way of doing this?
Upvotes: 0
Views: 79
Reputation:
If I did understand well, you are looking for this:
interface Ainterface<T extends AsuperPojo> {
void insertToDb(T foo);
}
then use:
class SubClass2 implements Ainterface<SpecialSubClass2Pojo>
Some reading: https://docs.oracle.com/javase/tutorial/java/generics/
Upvotes: 4