Java overriding parent equals method -
i have 2 classes person
, teacher
. in person
class check if 2 objects passed in equal using compareto method. in teacher
class, problem i'm working on states need override equals
method in person. in equals
method, way return true if it's equal in both equals
method in person
, teacher
. question is, when check in teacher
's equals
method, call super.equals(other)
in order check if 2 objects equal parent class or there else need do?
person:
public class person implements comparable<person> { public boolean equals(object other) { try { return this.compareto(other) == 0; }catch(exception e) { return false; } } }
teacher
public class teacher extends person { private string facultyid; @override public boolean equals(object other) { boolean personequals = super.equals(other); try { teacher teach1 = (teacher)other; boolean idequals = this.facultyid.equals(teach1.facultyid); if(idequals && personequals) return true; return false; }catch(exception e) { return false; } } }
basically, contract of object#equals
states:
it symmetric: non-null reference values x , y, x.equals(y) should return true if , if y.equals(x) returns true
and implementation of teacher#equals
doesn't meet requirement. cases when implementing equals
method in class inherits not object
e.g. teacher
, should verify if type of object compared the same as class you're comparing. achieve this, should use getclass().equals
:
public class teacher extends person { private string facultyid; @override public boolean equals(object other) { //this line nonsense, not persons teachers //boolean personequals = super.equals(other); //avoid using try-catch //try { //verify other object not null if (other == null) { return false; } //verify other object teacher, not super or subclass of if (this.getclass().equals(other.getclass()) { //here comes real check teacher otherteacher = (teacher)other; return this.facultyid.equals(otherteacher.facultyid); } return false; } }
do similar person
in case should not allow comparing against subclasses of it.
Comments
Post a Comment