Search code examples
javagenericsgeneric-programminggeneric-method

abstract function, parameter type extends class


I am building a library management application in Java.

I have an abstract class called Material. It has an abstract method called equals.

There is a subclass called Newspaper and it of course implements equals, with the exact same signature as equals has inside Material:

public <T extends Material> boolean equals(Class<T> elementoAComparar) {
    if (this.getTitulo().equals(elementoAComparar.getTitulo()) && this.getFechaPublicacion().equals(elementoAComparar.getFechaPublicacion())) {
        return true;
    } else {
        return false;
    }
}

Java cannot resolve any of the methods of elementoAComparar. They all exist in Newspaper which does extend Material.

I got some help on this thread of SO but I cannot make it really work.

I guess what I don't really get is how to use methods of a class which is working as a generic parameter.

I am sure this is really not that hard, but I have really little experience with Java, please don't be too hard on me :)

Thanks!


Solution

  • As @Ajit George mentioned, if you are trying to implement an equality method, then there are cleaner ways of doing it. However, if you simply want your code to compile and run, then you'll need to change the signature of your method. Java cannot resolve of the methods of elementoAComparar because Class does not have those methods, Material does.

    You'll need to change your equals method signature from

    public <T extends Material> boolean equals(Class<T> elementoAComparar)
    

    to

    public <T extends Material> boolean equals(T elementoAComparar)
    

    The first signature tells the Java that you will be passing an instance of a Class object. The second tells Java that you will be passing an instance of an object which is a Material.