Question

My Situation:

I have 3 Classes (For my Android-App) who extend a partially abstract Class, where i define and implement the function: deleteObject(); This Function accept a generic Type T.

public abstract class GenericDatabaseManager<T> {
    public void deleteObject (T inObject) {

        // want to execute the function inObject.getId(); 
        // who is defined in the Workout, Exercise and the User
        // class
        
    }
    
    ...
}

public class WorkoutManager extends GenericDatabaseManager<Workout> {
    deleteObject(Workout);
}

public class ExerciseManager extends GenericDatabaseManager<Exercise> {
    deleteObject(Exercise);
}

public class UserManager extends GenericDatabaseManager<User> {
    deleteObject(User);
}

Question:

How can i execute the

inObject.getId();

who is defined in the Workout, Exercise and the User class inside my

deleteObject(T inObject);

?

I hope my question is understandable and i'm happy about every answer. Maybe (I'm optimistic) someone can and will help me :-)

Best regards

Was it helpful?

Solution

You haven't placed any upper bound on T, so the compiler doesn't know that it's an object that has a getId() method.

You can create an interface:

interface HasId {
    public int getId();
}

Then restrict T to be a HasId:

public abstract class GenericDatabaseManager<T extends HasId> {

And your Workout, etc. classes can implement HasId.

Then the compiler has enough information to know that whatever T winds up being, it knows there is at least a getId() method that can be called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top