@EqualsAndHashCode(callSuper = true) Annotation in Java: Explained with Example
This is a Java annotation used to automatically generate the 'equals()' and 'hashCode()' methods for a class.
The 'callSuper=true' parameter indicates that the generated code should also call the 'equals()' and 'hashCode()' methods of the superclass, in addition to comparing the fields of the current class.
For example, consider the following class hierarchy:
public class Animal {
protected String name;
protected int age;
}
public class Dog extends Animal {
private String breed;
}
@EqualsAndHashCode(callSuper=true)
public class Labrador extends Dog {
private String color;
}
Here, the '@EqualsAndHashCode(callSuper=true)' annotation on the 'Labrador' class will generate 'equals()' and 'hashCode()' methods that compare the fields of the 'Labrador' class ('name', 'age', 'breed', and 'color') and also call the 'equals()' and 'hashCode()' methods of the superclass ('Dog' and 'Animal').
This ensures that equality and hash code calculation are consistent across the entire class hierarchy.
原文地址: https://www.cveoy.top/t/topic/mQkL 著作权归作者所有。请勿转载和采集!