jack
jack

Reputation: 19

Is it possible to extend a parametrized class to another parametrized class with one parameter inheriting from the first one?

I'm fairly new to Java so I don't know if this is a bad practice or even possible, but let's get to it.

I'm trying to understand the working of inheritance in a map. Let's say I have these three classes:

public abstract class Person{
    private String ssNumber;
    public void genericPersonMethod(){/*do thing*/}
}

public class Patient extends Person{
    private String patientID;
    public void specificPatientMethod(){/*do thing*/}
}

public class Medic extends Person{
    private String medicID;
    public void specificMedicMethod(){/*do thing*/}
}

}

And then I try to build some kind of crude database for each extended class. I've tried doing this:

public abstract class PersonDB extends HashMap<String, Person>{
    private RandomObject personDBGenericProperty;
    public void genericThingToDoWithAPersonDB(){}
}

public class PatientDB extends PersonDB{
    private RandomObject patientDBSpecificProperty;
    public void specificThingToDoWithaPatientDB(){}
}

But then I've found out it doesn't work and it can't extend PersonDB to another class effectively. If I just make some PatientDB extends PersonDB and MedicDB extends PersonDB, the problem is that I could theoretically insert both Patients and Medics, and I couldn't access either classes' specific methods because they're both considered Persons. Doing PatientList<String, Patient> extends PersonDB is even worse because it then accepts any kind of Object. I'm honestly lost about what to do next.

Also, even if this ends up being bad practice for whatever reason (in which case I'm willing to learn any available workaround), I'd still like to know if there's a way to do this in this specific manner, just out of curiosity.

Upvotes: 1

Views: 80

Answers (1)

Mureinik
Mureinik

Reputation: 311088

The best approach would probably be to parameterize the class of person in the map:

public abstract class PersonDB<P extends Person> extends HashMap<String, P> {
    private RandomObject personDBGenericProperty;
    public void genericThingToDoWithAPersonDB(){}
}

public class PatientDB extends PersonDB<Patient> {
    private RandomObject patientDBSpecificProperty;
    public void specificThingToDoWithAPatientDB(){}
}

Upvotes: 2

Related Questions