Overriding Predefined Methods In Java - Software Testing Help

文章推薦指數: 80 %
投票人數:10人

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 Mapmap=newHashMap(); map.put(e1,"C++"); map.put(e2,"Python"); //displaycontents for(EqualsHashCodeeh:map.keySet()){ System.out.println(map.get(eh).toString()); } } } Output: Inthisprogram,weuseahashMap.Wehaveoverriddenbothequals()andhashCode()methods.Sowhenwesaymap.put(e1,“C++”),ithashestosomebucketlocation.Next,wecallamap.put(e2,“Python”).Thistimeitwillhashtothesamebucketandreplacethepreviousvalue.ThisisbecausewehaveoverriddenthehashCode()method. OverridingStaticMethodInJava CanweoverridethestaticmethodinJava? AsfarasoverridingthestaticmethodinJavaisconcerned,thedirectreplytothisquestionisNo,wecannotoverridethestaticmethod. Thestaticmethodisinvokedusingtheclassnameitself.Wedonotneedanobjecttocallastaticmethod.Soevenifwedeclareamethodwiththesameprototypeinasubclass,wecannotcallitoverriding.Instead,wearejusthidingtheparentclassdefinitionofthestaticmethod. ThefollowingJavaprogramshowsthestaticmethodandnon-staticmethodinaninheritancesystemalongwiththeirbehavioratruntime. classParent{ //ParentclassstaticmethodcannotbeoverriddenbyChild publicstaticvoiddisplay(){ System.out.println("Parentclass::staticdisplay()"); } //parentclassnon-staticprintmethodtobeoverriddenbyChild publicvoidprint(){ System.out.println("Parentclass::non-staticprint()"); } } //Subclass classChildextendsParent{ //staticdisplay()method=>hidesdisplay()inParentclass publicstaticvoiddisplay(){ System.out.println("Childclass::staticdisplay()"); } //overridesprint()inParentclass publicvoidprint(){ System.out.println("Childclass::Non-staticprint()"); } } publicclassMain{ publicstaticvoidmain(Stringargs[]){ Parentnew_obj=newChild(); //staticmethodsarecallasperthereferencetype.Sincereferencetype //Parent,thiscallwillexecuteParentclass'sdisplaymethod new_obj.display(); //heretheprint()methodofChildclassiscalled new_obj.print(); } } Output: Fromtheprogramoutput,wecanconcludethefollowing. Thecalltothestaticmethodisalwaysmadebasedonthetypeofreference.Hencewhenwecallednew_obj.display()intheaboveprogram,asthenew_objreferenceisoftypeclassParent,thedisplay()methodofParentclassiscalled. Ontheotherhand,non-staticmethodsarecalledbasedonthecontentsofthereferenceobjectwithwhichthemethodiscalled.Henceintheaboveprogramnew_obj.print()methodcallstheprint()methodofthechildclassasnew_objcontentsaretheobjectofthechildclass. ThisexplainstheoutputoftheprogramaboveandweneedtorememberthefollowingpointsaswellwhiledealingwithstaticmethodsintheOOPsystem. Astaticmethodcannothideanon-staticinstancemethodandanon-staticinstancemethodcannotoverrideastaticmethod. Wecanoverloadthemethodsfromtheparentclassinasubclassbuttheyneitheroverridenorhidetheparentclassmethods,rathertheyarenewmethodsinthesubclass. OverridingcompareTo()InJava Weknowthattheinterfacejava.lang.Comparableprovidesa‘compareTo()’methodusingwhichwecansorttheobjectsinanaturalorderlikelexicalorderforStringobjects,numericorderforIntegers,etc. Toimplementsortinginuser-definedobjectsorcollections,weneedtooverridethecompareTo()methodtosortthecollectionelementsoruser-definedobjects. SowhatacompareTo()methoddoes? AcompareTo()methodmustreturnpositivevalueifthecurrentobjectisgreaterthanthepassedobjectinorderandthenegativevalueofthecurrentobjectislesserthanthepassedobject.Ifboththeobjectsareequal,thenthecompareTo()methodwillreturnzero. Anotherpointtonoteisthatthemethodequals()andcompareTo()shouldbehaveconsistentlywitheachother.ThismeansthatifthecompareTo()methodreturnsthattwoobjectsareequal(returnszero)thenweshouldhavethesameoutputfromtheequals()methodaswell. Let’simplementaJavaprogramthatoverridesthecompareTo()method.Inthisprogram,weareusingaColorclassthathastwoprivatevariablesi.e.nameandid.Wehaveassociatedthe‘id’witheachcolorandwewilloverridethecompare()methodtoarrangecolorsaccordingtotheid. importjava.util.*; //colorclass classColorimplementsComparator,Comparable{ privateStringname; privateintid; Color(){ } Color(Stringn,intid){ this.name=n; this.id=id; } publicStringgetColorName(){ returnthis.name; } publicintgetColorId(){ returnthis.id; } //OverridingthecompareTomethod @OverridepublicintcompareTo(Colorc){ return(this.name).compareTo(c.name); } //Overridingthecomparemethodtosortthecolorsonid @Overridepublicintcompare(Colorc,Colorc1){ returnc.id-c1.id; } } publicclassMain{ publicstaticvoidmain(Stringargs[]){ //ListofColors Listlist=newArrayList(); list.add(newColor("Red",3)); list.add(newColor("Green",2)); list.add(newColor("Blue",5)); list.add(newColor("Orange",4)); list.add(newColor("Yellow",1)); Collections.sort(list);//Sortsthearraylist System.out.println("Thelistofcolors:"); for(Colorc:list)//printthesortedlistofcolors System.out.print(c.getColorName()+","); //Sortthearraylistusingcomparator Collections.sort(list,newColor()); System.out.println(""); System.out.println("Thesortedlistofcolors:"); for(Colorc:list)//printthesortedlistofcolorsasperid System.out.print(c.getColorId()+":"+c.getColorName()+","); } Output: Intheaboveoutput,wefirstdisplaythelistofcolorsandthenthesortedlistofcolors.Intheprogram,wehaveoverriddencompareTo()andcompare()methods. OverridetoString()MethodInJava Themethod‘toString()’returnstheStringrepresentationofanobjectinJava.Butwhenwehaveuser-definedobjects,thenthismethodmaybehavedifferently. Forexample,considerthefollowingprogram. classComplex{ privatedoubler,i; publicComplex(doubler,doublei){ this.r=r; this.i=i; } } publicclassMain{ publicstaticvoidmain(String[]args){ Complexc1=newComplex(5,20);//createcomplexclassObject //printthecontentsofcomplexnumber System.out.println("Complexnumbercontents:"+c1); } } Output: AsshowninthisprogramwearedisplayingtheComplexclassobjectwhichwehavedefinedearlier.However,theoutputshownisnotthecontentsbutit’srathercryptic. TheoutputshowsaclassnameComplexfollowedby‘@’characterandthenthehashCodeoftheobject.ThisisthedefaultoutputprintedbythetoString()methodoftheObjectclass. IfwewanttheproperoutputthenweneedtooverridethetoString()methodinourapplication. ThefollowingJavaprogramshowshowtooverridethetoString()methodtoprintthecontentsoftheComplexobject. classComplex{ privatedoubler,i; publicComplex(doubler,doublei){ this.r=r; this.i=i; } //overridetoString()methodtoreturnStringrepresentationofcomplexnumber @Override publicStringtoString(){ returnString.format(r+"+i"+i); } } publicclassMain{ publicstaticvoidmain(String[]args){ Complexc1=newComplex(10,15); System.out.println("ComplexNumbercontents:"+c1); } } Output: TheaboveprogramshowsthatthetoString()methodisoverriddentoreturnthecontentsofComplexobjectinthegivenformat(real+i*imaginary). Ingeneral,whenwewanttodisplaytheclassobjectusingeitherprint()orprintln()thenitisalwaysadvisabletooverridethetoString()methodsothatwegettheproperoutput. FrequentlyAskedQuestions Q#1)Whyuse.equalsinsteadof==Java? Answer:Weuse‘==’tocompareprimitivetypeslikeint,char,boolean,etc.Weuseequals()tocompareobjects(predefinedoruser-defined).Weusuallyoverridetheequals()methodtocomparetwoobjectsandthereturnvalueoftheequals()dependsontheoverriddencode. Q#2)WhatishashCode()andequals()usedfor? Answer:InJava,theequals()methodisusedtocomparetheequalityoftwoobjects.ThehashCode()methodreturnsthehashCodeoftheobject.Whiletheequals()methodisusedwithmostobjectstotesttheirequality,thehashCodeismostlyusedinhashcollectionslikeHashTable,HashMap,HashSet,etc. Q#3)Canwechangetheargumentlistoftheoverriddenmethod? Answer:No.Whenweoverridethemethod,wekeepthemethodsignatureorprototypeofthemethodthesameinthesubclassaswell.Sowecannotchangethenumberofparametersintheoverriddenmethod. Q#4)WhydoweoverridetoString()? Answer:WhenthetoString()methodisoverridden,wecanreturnthevaluesoftheobjectforwhichthetoString()methodisoverriddenwithoutwritingtoomuchcode.ThisisbecausethejavacompilerinvokesthetoString()methodwhenweprintanobject. Q#5)WhatwouldhappenifyouwillnotoverridethetoString()method? Answer:IfwedonotoverridethetoString()method,thenwewillnotgetanyinformationaboutthepropertiesorstateoftheobject.Wewillnotknowwhatisactuallyinsidetheobject.SoalltheclassesshouldoverridethetoString()method. ThisisbecausethedefaultimplementationofthetoString()methoddisplaystheStringrepresentationbutwhenweusedefaulttoString()implementationontheobjectthenwewillnotgetthecontentsoftheobject. Conclusion Inthistutorial,wediscussedonoverridingafewpredefinedJavamethodsandwealsosawwhyweneedtooverridethem. Whenwedealwithobjects,thedefaultimplementationsofmethodslikeequals(),compareTo(),andtoString()maynotgivethecorrectinformation.Hencewegoforoverriding. =>TakeALookAtTheJavaBeginnersGuideHere. RecommendedReading JavaStringMethodsTutorialWithExamples JavaThreadswithMethodsandLifeCycle JavaStringlength()MethodWithExamples ReverseAnArrayInJava-3MethodsWithExamples HowToUseJavatoStringMethod? JavaStringindexOfMethodWithCodeExamples JavaStringcontains()MethodTutorialWithExamples JavaStringSplit()Method–HowToSplitAStringInJava AboutSoftwareTestingHelpHelpingourcommunitysince2006! MostpopularportalforSoftwareprofessionalswith240million+visitsand300,000+followers!YouwillabsolutelyloveourcreativecontentonSoftwareToolsandServicesReviews! RecommendedReading JavaStringMethodsTutorialWithExamples JavaThreadswithMethodsandLifeCycle JavaStringlength()MethodWithExamples ReverseAnArrayInJava–3MethodsWithExamples HowToUseJavatoStringMethod? JavaStringindexOfMethodWithCodeExamples JavaStringcontains()MethodTutorialWithExamples JavaStringSplit()Method–HowToSplitAStringInJava JOINOurTeam!



請為這篇文章評分?