Overriding Predefined Methods In Java - Software Testing Help
文章推薦指數: 80 %
Java has various predefined methods like equals (), hashCode (), compareTo (), toString (), etc. that are used commonly for general objects ...
Skiptocontent
Menu
MENUMENUHomeResourcesFREEeBooksQATesting
FreeQATrainingTestCasesSDLCTestLink
SoftwareTestingBugZillaMobileTestingJIRA
AgileMethodologyDatabaseTestingETLTesting
QualityAssuranceTestManagementSAPERPTesting
Courses
SoftwareTesting(LIVECourse)Selenium(LIVECourse)
SoftwareTestingSeleniumQTP/UFTJIRAVideosRubyCucumber
Automation
AutomationTestingSoapUIJIRAAppiumKarateFramework
SeleniumQTP/UFTALMQCPostman
JMeterLoadRunnerAPITestingRobotFramework
TestNGJUnitEclipseMaven
TypesOfTesting
AllTestingTypesRegressionTestingUnitTestingSmokeTesting
FunctionalTestingIntegrationTestingSystemTestingUsabilityTesting
UATTestingBetaTestingBlackBoxTestingWhiteBoxtesting
LoadTestingStressTestingSecurityTestingPerformanceTesting
Tutorials
C++C#DevOpsVBScriptTeamManagementComputerNetworkingJest
PythonJAVAUNIXSVNAngularJSSpockLaravel
SpecFlowJSONFlaskSOAtestMockitoKarma
MachineLearningBlockchainGitHubGatlingWiremock
Data
OraclePL/SQL
DataWarehouseExcelVBA
BigDataJDBC
MongoDB
Menu
MENUMENUHomeResourcesFREEeBooksQATesting
FreeQATrainingTestCasesSDLCTestLink
SoftwareTestingBugZillaMobileTestingJIRA
AgileMethodologyDatabaseTestingETLTesting
QualityAssuranceTestManagementSAPERPTesting
Courses
SoftwareTesting(LIVECourse)Selenium(LIVECourse)
SoftwareTestingSeleniumQTP/UFTJIRAVideosRubyCucumber
Automation
AutomationTestingSoapUIJIRAAppiumKarateFramework
SeleniumQTP/UFTALMQCPostman
JMeterLoadRunnerAPITestingRobotFramework
TestNGJUnitEclipseMaven
TypesOfTesting
AllTestingTypesRegressionTestingUnitTestingSmokeTesting
FunctionalTestingIntegrationTestingSystemTestingUsabilityTesting
UATTestingBetaTestingBlackBoxTestingWhiteBoxtesting
LoadTestingStressTestingSecurityTestingPerformanceTesting
Tutorials
C++C#DevOpsVBScriptTeamManagementComputerNetworkingJest
PythonJAVAUNIXSVNAngularJSSpockLaravel
SpecFlowJSONFlaskSOAtestMockitoKarma
MachineLearningBlockchainGitHubGatlingWiremock
Data
OraclePL/SQL
DataWarehouseExcelVBA
BigDataJDBC
MongoDB
LastUpdated:August7,2022
Thistutorialexplainshowtooverridepredefinedmethodslikeequals(),hashCode(),compareTo(),etc.inJavawithexamples:
Inourprevioustutorial,wediscussedruntimepolymorphisminJava.RuntimepolymorphisminJavaisimplementedusingmethodoverriding.Methodoverridinginvolvesredefiningtheparentclassmethodinthesubclass.
Javahasvariouspredefinedmethodslikeequals(),hashCode(),compareTo(),toString(),etc.thatareusedcommonlyforgeneralobjectsirrespectiveofwhichclasstheybelongto.Butforthesemethodstoworkforallobjects,weneedtooverridethesemethodsorredefinetheirimplementationssothattheycanworkwiththedatawewant.
=>VisitHereToLearnJavaFromScratch.
Inthistutorial,wewilldiscusstheoverridingofallthesemethodsalongwiththeconsequencesifwedonotoverridethesemethods.
WhatYouWillLearn:Overridingequals()AndhashCode()MethodsInJavaOverridingStaticMethodInJavaOverridingcompareTo()InJavaOverridetoString()MethodInJavaFrequentlyAskedQuestionsConclusionRecommendedReading
Overridingequals()AndhashCode()MethodsInJava
Weusetheequals()methodinJavatocomparetwoobjects.Thismethodreturnstruewhentheobjectsareequalandfalsewhennotequal.
Twowaysareusedtocomparetheequalityoftwoobjects.
#1)ShallowComparison
Shallowcomparisonisthedefaultimplementationfortheequals()methoddefinedin“java.lang.Object”class.Asapartofthisimplementation,theequals()methodwillcheckiftwoobjectsbeingcomparedhavereferencesreferringtothesameobject.
Thismeansthatifobj1andobj2aretwoobjects,thenthedefaultimplementationoftheequals()method(shallowcomparison)willonlycheckifthereferencesofobj1andobj2arefromthesameobject.
Inshallowcomparison,nodatacontentsarecompared.
#2)DeepComparison
Indeepcomparison,wecomparethedatamembersofeachobjecti.e.theobjectsarecomparedwithrespecttothestate.Sowecomparetheobjectsatadeeplevelincludingitscontents.
Tocomparetheobjectsusingdeepcomparisonweusuallyoverridetheequals()method.
NowconsiderthefollowingJavaprogram.
classComplex{
privatedoubler,i;//declarerealandimaginarycomponentasprivate
publicComplex(doubler,doublei){//constructor
this.r=r;
this.i=i;
}
}
publicclassMain{
publicstaticvoidmain(String[]args){
Complexc1=newComplex(5,10);//c1object
Complexc2=newComplex(5,10);//c2object
if(c1==c2){
System.out.println("TwoComplexobjectsareEqual");
}else{
System.out.println("TwoComplexobjectsarenotEqual");
}
}
}
Output:
Ifweseetheoutputoftheaboveprogram,itsaysthattheobjectsarenotequaleventhoughthecontentsofthetwoobjectsarethesame.Thisisbecause,whentheequalityischecked,itisdeterminedaswhetherthetwoobjectsc1andc2refertothesameobject.
Asseenintheprogramc1andc2aretwodifferentobjects,sotheyaredifferentreferencesandtherebyisresultedso.
Nowlet’screateathirdreferencec3andequateittoc1asfollows:
Complexc3=c1;
Inthiscase,c3andc1willrefertothesameobject,andhence(c3==c1)willreturntrue.
Whattheaboveprogramdidwastheshallowcomparison.Sohowdowecheckiftwoobjectsarethesamecontent-wise?
Here,wegoforadeepcomparison,andforthispurpose,weoverridetheequals()method.
Thefollowingprogramshowstheoverridingoftheequals()method.WeusethesameComplexclass.
classComplex{
privatedoubler,i;
publicComplex(doubler,doublei){
this.r=r;
this.i=i;
}
//overrideequals()methodtocomparetwocomplexobjects
@Override
publicbooleanequals(Objectobj){
//returnstrue=>objectiscomparedtoitself
if(obj==this){
returntrue;
}
//returnfalseifobjisnotaninstanceofComplexclass
if(!(objinstanceofComplex)){
returnfalse;
}
//typecastobjtoComplextype
Complexc=(Complex)obj;
//Comparethecontentsoftwoobjectsandreturnvalue
returnDouble.compare(r,c.r)==0
&&Double.compare(i,c.i)==0;
}
}publicclassMain{
publicstaticvoidmain(String[]args){
Complexc1=newComplex(5,10);
Complexc2=newComplex(5,10);
if(c1.equals(c2)){
System.out.println("Complexobjectsc1andc2areEqual");
}else{
System.out.println("Complexobjectsc1andc2arenotEqual");
}
}
}
Output:
Nowthatwehaveanoverriddenequals()method,whenwecomparetwoobjects,theoutputshowsthatthetwoobjectsareequalastheircontentsarethesame.Notetheoverriddenequals()method.Herewecheckifboththeobjectshavethesamereference.Ifnotthenweindividuallycheckthecontentsoftheseobjects.
InJava,wheneverweoverridetheequals()method,itisadvisabletooverridethehashCode()methodaswell.ThisisbecauseifwedonotoverridethehashCode()method,theneachobjectmayhavedifferenthashCode.
Thismaynotinterferewiththegeneralobjectsbutcertainhash-basedcollectionslikeHashTable,HashSet,andHashMapmaynotworkproperly.
Thefollowingprogramshowsequals()andhashCode()methodsoverridden.
importjava.io.*;
importjava.util.*;
classEqualsHashCode{
Stringname;
intid;
EqualsHashCode(Stringname,intid){
this.name=name;
this.id=id;
}
@Override
publicbooleanequals(Objectobj){
//bothobjectsrefertosameobject
if(this==obj)
returntrue;
//objisnotaninstanceofEqualsHashCode
if(obj==null||obj.getClass()!=this.getClass())
returnfalse;
//typecastobj
EqualsHashCodeo_obj=(EqualsHashCode)obj;
//comparetheobjects
return(o_obj.name.equals(this.name)&&o_obj.id==this.id);
}
@Override
publicinthashCode(){
//returncurrentobject'sidashashCode
returnthis.id;
}
}
classMain{
publicstaticvoidmain(String[]args){
//createtwoobjectswithsamestate
EqualsHashCodee1=newEqualsHashCode("Java",1);
EqualsHashCodee2=newEqualsHashCode("Java",1);
//updatetheobjects
Map
延伸文章資訊
- 1Java Methods (With Examples) - Programiz
Java Methods · User-defined Methods: We can create our own method based on our requirements. Stan...
- 2Methods in Java | Types, Method Signature, Example
Predefined methods in Java are those methods that are already defined in the Java API (Applicatio...
- 3Method in Java - Javatpoint
In Java, predefined methods are the method that is already defined in the Java class libraries is...
- 4Overriding Predefined Methods In Java - Software Testing Help
Java has various predefined methods like equals (), hashCode (), compareTo (), toString (), etc. ...
- 5What are predefined methods in java - Linux Hint
In java, the methods that are ready-to-use are known as the predefined methods. These methods com...