What is Class and Object in Java OOPS? Learn with Example

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

Understand the concept of Java Classes and Objects with an example. · Class – Dogs · Data members or objects– size, age, color, breed, etc. Skiptocontent ClassesandObjectsinJavaarethefundamentalcomponentsofOOP’s.Oftenthereisaconfusionbetweenclassesandobjects.Inthistutorial,wetrytotellyouthedifferencebetweenClassandObjectinJava. First,let’sunderstandwhattheyare, WhatisClassinJava? WhatisanObjectinJava? WhatistheDifferenceBetweenObjectandClassinJava? ConceptofClassesandObjects ClassesandObjectsinJavaExamplePrograms JavaObjectandClassExample:mainoutsideclass WhatisClassinJava? Classareablueprintorasetofinstructionstobuildaspecifictypeofobject.ItisabasicconceptofObject-OrientedProgrammingwhichrevolvearoundthereal-lifeentities.ClassinJavadetermineshowanobjectwillbehaveandwhattheobjectwillcontain. SyntaxofClassinJava class{ field; method; } WhatisObjectinJava? Objectisaninstanceofaclass.AnobjectinOOPSisnothingbutaself-containedcomponentwhichconsistsofmethodsandpropertiestomakeaparticulartypeofdatauseful.Forexamplecolorname,table,bag,barking.Whenyousendamessagetoanobject,youareaskingtheobjecttoinvokeorexecuteoneofitsmethodsasdefinedintheclass. Fromaprogrammingpointofview,anobjectinOOPScanincludeadatastructure,avariable,orafunction.Ithasamemorylocationallocated.JavaObjectsaredesignedasclasshierarchies. ObjectSyntaxinJava ClassNameReferenceVariable=newClassName(); WhatistheDifferenceBetweenObjectandClassinJava? AClassinobjectorientedprogrammingisablueprintorprototypethatdefinesthevariablesandthemethods(functions)commontoallJavaObjectsofacertainkind. AnobjectinOOPSisaspecimenofaclass.Softwareobjectsareoftenusedtomodelreal-worldobjectsyoufindineverydaylife. Clickhereifthevideoisnotaccessible UnderstandtheconceptofJavaClassesandObjectswithanexample. Let’stakeanexampleofdevelopingapetmanagementsystem,speciallymeantfordogs.Youwillneedvariousinformationaboutthedogslikedifferentbreedsofthedogs,theage,size,etc. Youneedtomodelreal-lifebeings,i.e.,dogsintosoftwareentities. Moreover,themilliondollarquestionis,howyoudesignsuchsoftware? Hereisthesolution- First,let’sdoanexercise. Youcanseethepictureofthreedifferentbreedsofdogsbelow. Stophererightnow!Listdownthedifferencesbetweenthem. Someofthedifferencesyoumighthavelistedoutmaybebreed,age,size,color,etc.Ifyouthinkforaminute,thesedifferencesarealsosomecommoncharacteristicssharedbythesedogs.Thesecharacteristics(breed,age,size,color)canformadatamembersforyourobject. Next,listoutthecommonbehaviorsofthesedogslikesleep,sit,eat,etc.Sothesewillbetheactionsofoursoftwareobjects. Sofarwehavedefinedfollowingthings, Class–Dogs Datamembersorobjects–size,age,color,breed,etc. Methods–eat,sleep,sitandrun. Now,fordifferentvaluesofdatamembers(breedsize,age,andcolor)inJavaclass,youwillgetdifferentdogobjects. YoucandesignanyprogramusingthisOOPsapproach. Whilecreatingaclass,onemustfollowthefollowingprinciples. SingleResponsibilityPrinciple(SRP)-Aclassshouldhaveonlyonereasontochange OpenClosedResponsibility(OCP)-Itshouldbeabletoextendanyclasseswithoutmodifyingit LiskovSubstitutionResponsibility(LSR)-Derivedclassesmustbesubstitutablefortheirbaseclasses DependencyInversionPrinciple(DIP)-Dependonabstractionandnotonconcretions InterfaceSegregationPrinciple(ISP)-Preparefinegrainedinterfacesthatareclientspecific. ClassesandObjectsinJavaExamplePrograms //ClassDeclaration publicclassDog{ //InstanceVariables Stringbreed; Stringsize; intage; Stringcolor; //method1 publicStringgetInfo(){ return("Breedis:"+breed+"Sizeis:"+size+"Ageis:"+age+"coloris:"+color); } publicstaticvoidmain(String[]args){ Dogmaltese=newDog(); maltese.breed="Maltese"; maltese.size="Small"; maltese.age=2; maltese.color="white"; System.out.println(maltese.getInfo()); } } Output: Breedis:MalteseSizeis:SmallAgeis:2coloris:white JavaObjectandClassExample:mainoutsideclass Inpreviousprogram,wearecreatingmain()methodinsidetheclass.Now,wecreateclassesanddefinemain()methodinanotherclass.Thisisabetterwaythanpreviousone. //ClassDeclaration classDog{ //InstanceVariables Stringbreed; Stringsize; intage; Stringcolor; //method1 publicStringgetInfo(){ return("Breedis:"+breed+"Sizeis:"+size+"Ageis:"+age+"coloris:"+color); } } publicclassExecute{ publicstaticvoidmain(String[]args){ Dogmaltese=newDog(); maltese.breed="Maltese"; maltese.size="Small"; maltese.age=2; maltese.color="white"; System.out.println(maltese.getInfo()); } } Output: Breedis:MalteseSizeis:SmallAgeis:2coloris:white Summary: JavaClassisanentitythatdetermineshowJavaObjectswillbehaveandwhatobjectswillcontain AJavaobjectisaself-containedcomponentwhichconsistsofmethodsandpropertiestomakecertaintypeofdatauseful Aclasssystemallowstheprogramtodefineanewclass(derivedclass)intermsofanexistingclass(superclass)byusingatechniquelikeinheritance,overridingandaugmenting. YouMightLike: HowtoCreateUserDefinedExceptioninJava JavaStringindexOf()MethodwithSubstring&Examples HowtoReverseaStringinJavausingRecursion Top25ScalaInterviewQuestionsandAnswers(PDF) DifferencebetweenComparableandComparatorinJava Postnavigation ReportaBug Previous PrevNextContinue Scrolltotop ToggleMenuClose Searchfor: Search



請為這篇文章評分?