简体   繁体   中英

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!

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 .

Two points:

  • Class objects represent the object class, and equals is typically used to compare instances. Your equals declaration implies you want to compare this object with a class object.
  • equals is defined on java.lang.Object , which all objects inherit. In order for your comparison implementation to work with Java library code, you need to override Object.equals . equals predates generics in Java, so Object.equals does not use them. Your implementation needs to check the instance being compared and cast it to your object type in order to get at the fields of the other object.

The answer at What issues should be considered when overriding equals and hashCode in Java? provides a good summary and demonstration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM