How to make an interface method receive any object (Object type) as parameter?

Asked

Viewed 56 times

3

I’m studying polymorphism now, and I’m not getting it.

Given the interface:

public interface View {
    public boolean existe(Object obj);
}

I have this method, which I would like to be implemented from the interface

public boolean existe(Diretor diretor) {
    for (Diretor d : this.tmDiretor.getLstDiretores()) {
        if (d.getId().equals(diretor.getId()))
            return true;
    }
    return false;
}

But I would like the interface parameter to accept whichever object of the type Object, as Cliente, Diretor, Secretário, etc., according to your call.

1 answer

5


You’re using the wrong mechanism. In this case it’s not to use this kind of polymorphism. It’s to use parametric polymorphism. Something like this:

public interface View<T extends Role> {
    public boolean existe(T obj);
}

public class AlgumaClasse implements Role<Diretor> {
    public boolean existe(Diretor diretor) {
        for (Diretor d : this.tmDiretor.getLstDiretores()) if (d.getId().equals(diretor.getId())) return true;
        return false;
    }
}

I put in the Github for future reference.

Note that Diretor and other roles you want to use in this way should inherit from Role. It could be another type, but it needs to have a type in common. It can be Object? It can because it is a common type of all objects, but the more restricted this hierarchy the better. To tell the truth the way it is the interface loses half the sense.

But it may not even need this in some circumstances as long as the same processing is applicable to all objects of the type Role. You could even have the implementation on the interface itself. I won’t post here because I don’t know if it’s possible for your case.

If all this is too confusing you probably need to learn some concepts before moving on to the one that is a little more advanced.

And there seem to be other problems, even conceptual problems in this code, but I can’t claim seeing so little. If there is, all this matters little because doing something right on top of something wrong gets wrong the same way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.