check two objects are the same according to their property in JAVA -
for example:
public class fruit{ private string color; private double weight; ... public boolean equals(fruit a){ homecoming (this.getcolor().equals(a.getcolor()) && (this.getweight()==a.getweight())); } } public class orange extends fruit{ public orange(double weight) { super("orange", weight); } } public class navalorange extends orange{ public navalorange(double weight) { super(weight); } } then wrote test check 2 objects if same.
orange orange = new orange(8); navalorange navalorange = new navalorange(8); assertequals(orange, navalorange); but keeps returning errors:
junit.framework.assertionfailederror: expected:<orange@5305068a> was:<navalorange@1f32e575> can explain why happening? think may wrong @ tostring method.
there no equals(fruit) method in object. equals method should start like...
@override public boolean equals(object a) { boolean equals = false; if (a instanceof fruit) { ... } homecoming equals; } basically, assertequals doing using object#equals. can test adding @override annotation equals method , produce compiler error, `equals(fruit) not override method it's parent...
also, if override equals, should override hashcode in order maintain it's contract...
from javadocs object#equals
note necessary override hashcode method whenever method overridden, maintain general contract hashcode method, states equal objects must have equal hash codes.
java
No comments:
Post a Comment