Objects and Classes in Java - Javatpoint

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

Class in Java ⇧SCROLLTOTOP Home Java Programs OOPs String Exception Multithreading Collections JavaFX JSP Spring SpringBoot Projects InterviewQuestions BasicsofJava JavaObjectClass JavaOOPsConcepts NamingConvention ObjectandClass Method Constructor statickeyword thiskeyword JavaInheritance Inheritance(IS-A) Aggregation(HAS-A) JavaPolymorphism MethodOverloading MethodOverriding CovariantReturnType superkeyword InstanceInitializerblock finalkeyword RuntimePolymorphism DynamicBinding instanceofoperator JavaAbstraction Abstractclass Interface AbstractvsInterface JavaEncapsulation Package AccessModifiers Encapsulation JavaArray JavaArray JavaOOPsMisc Objectclass ObjectCloning Mathclass WrapperClass JavaRecursion CallByValue strictfpkeyword javadoctool CommandLineArg ObjectvsClass OverloadingvsOverriding JavaString JavaRegex ExceptionHandling JavaInnerclasses JavaMultithreading JavaI/O JavaNetworking JavaAWT&Events JavaSwing JavaFX JavaApplet JavaReflection JavaDate JavaConversion JavaCollection JavaJDBC JavaNewFeatures RMI Internationalization InterviewQuestions next→ ←prev ObjectsandClassesinJava ObjectinJava ClassinJava InstanceVariableinJava MethodinJava ExampleofObjectandclassthatmaintainstherecordsofstudent AnonymousObject Inthispage,wewilllearnaboutJavaobjectsandclasses.Inobject-orientedprogrammingtechnique,wedesignaprogramusingobjectsandclasses. AnobjectinJavaisthephysicalaswellasalogicalentity,whereas,aclassinJavaisalogicalentityonly. WhatisanobjectinJava Anentitythathasstateandbehaviorisknownasanobjecte.g.,chair,bike,marker,pen,table,car,etc.Itcanbephysicalorlogical(tangibleandintangible).Theexampleofanintangibleobjectisthebankingsystem. Anobjecthasthreecharacteristics: State:representsthedata(value)ofanobject. Behavior:representsthebehavior(functionality)ofanobjectsuchasdeposit,withdraw,etc. Identity:AnobjectidentityistypicallyimplementedviaauniqueID.ThevalueoftheIDisnotvisibletotheexternaluser.However,itisusedinternallybytheJVMtoidentifyeachobjectuniquely. ForExample,Penisanobject.ItsnameisReynolds;coloriswhite,knownasitsstate.Itisusedtowrite,sowritingisitsbehavior. Anobjectisaninstanceofaclass.Aclassisatemplateorblueprintfromwhichobjectsarecreated.So,anobjectistheinstance(result)ofaclass. ObjectDefinitions: Anobjectisareal-worldentity. Anobjectisaruntimeentity. Theobjectisanentitywhichhasstateandbehavior. Theobjectisaninstanceofaclass. WhatisaclassinJava Aclassisagroupofobjectswhichhavecommonproperties.Itisatemplateorblueprintfromwhichobjectsarecreated.Itisalogicalentity.Itcan'tbephysical. AclassinJavacancontain: Fields Methods Constructors Blocks Nestedclassandinterface Syntaxtodeclareaclass: class{ field; method; } InstancevariableinJava Avariablewhichiscreatedinsidetheclassbutoutsidethemethodisknownasaninstancevariable.Instancevariabledoesn'tgetmemoryatcompiletime.Itgetsmemoryatruntimewhenanobjectorinstanceiscreated.Thatiswhyitisknownasaninstancevariable. MethodinJava InJava,amethodislikeafunctionwhichisusedtoexposethebehaviorofanobject. AdvantageofMethod CodeReusability CodeOptimization newkeywordinJava Thenewkeywordisusedtoallocatememoryatruntime.AllobjectsgetmemoryinHeapmemoryarea. ObjectandClassExample:mainwithintheclass Inthisexample,wehavecreatedaStudentclasswhichhastwodatamembersidandname.WearecreatingtheobjectoftheStudentclassbynewkeywordandprintingtheobject'svalue. Here,wearecreatingamain()methodinsidetheclass. File:Student.java //JavaProgramtoillustratehowtodefineaclassandfields //DefiningaStudentclass. classStudent{ //definingfields intid;//fieldordatamemberorinstancevariable Stringname; //creatingmainmethodinsidetheStudentclass publicstaticvoidmain(Stringargs[]){ //Creatinganobjectorinstance Students1=newStudent();//creatinganobjectofStudent //Printingvaluesoftheobject System.out.println(s1.id);//accessingmemberthroughreferencevariable System.out.println(s1.name); } } TestitNow Output: 0 null ObjectandClassExample:mainoutsidetheclass Inrealtimedevelopment,wecreateclassesanduseitfromanotherclass.Itisabetterapproachthanpreviousone.Let'sseeasimpleexample,wherewearehavingmain()methodinanotherclass. WecanhavemultipleclassesindifferentJavafilesorsingleJavafile.IfyoudefinemultipleclassesinasingleJavasourcefile,itisagoodideatosavethefilenamewiththeclassnamewhichhasmain()method. File:TestStudent1.java //JavaProgramtodemonstratehavingthemainmethodin //anotherclass //CreatingStudentclass. classStudent{ intid; Stringname; } //CreatinganotherclassTestStudent1whichcontainsthemainmethod classTestStudent1{ publicstaticvoidmain(Stringargs[]){ Students1=newStudent(); System.out.println(s1.id); System.out.println(s1.name); } } TestitNow Output: 0 null 3Waystoinitializeobject Thereare3waystoinitializeobjectinJava. Byreferencevariable Bymethod Byconstructor 1)ObjectandClassExample:Initializationthroughreference Initializinganobjectmeansstoringdataintotheobject.Let'sseeasimpleexamplewherewearegoingtoinitializetheobjectthroughareferencevariable. File:TestStudent2.java classStudent{ intid; Stringname; } classTestStudent2{ publicstaticvoidmain(Stringargs[]){ Students1=newStudent(); s1.id=101; s1.name="Sonoo"; System.out.println(s1.id+""+s1.name);//printingmemberswithawhitespace } } TestitNow Output: 101Sonoo Wecanalsocreatemultipleobjectsandstoreinformationinitthroughreferencevariable. File:TestStudent3.java classStudent{ intid; Stringname; } classTestStudent3{ publicstaticvoidmain(Stringargs[]){ //Creatingobjects Students1=newStudent(); Students2=newStudent(); //Initializingobjects s1.id=101; s1.name="Sonoo"; s2.id=102; s2.name="Amit"; //Printingdata System.out.println(s1.id+""+s1.name); System.out.println(s2.id+""+s2.name); } } TestitNow Output: 101Sonoo 102Amit 2)ObjectandClassExample:Initializationthroughmethod Inthisexample,wearecreatingthetwoobjectsofStudentclassandinitializingthevaluetotheseobjectsbyinvokingtheinsertRecordmethod. Here,wearedisplayingthestate(data)oftheobjectsbyinvokingthedisplayInformation()method. File:TestStudent4.java classStudent{ introllno; Stringname; voidinsertRecord(intr,Stringn){ rollno=r; name=n; } voiddisplayInformation(){System.out.println(rollno+""+name);} } classTestStudent4{ publicstaticvoidmain(Stringargs[]){ Students1=newStudent(); Students2=newStudent(); s1.insertRecord(111,"Karan"); s2.insertRecord(222,"Aryan"); s1.displayInformation(); s2.displayInformation(); } } TestitNow Output: 111Karan 222Aryan Asyoucanseeintheabovefigure,objectgetsthememoryinheapmemoryarea.Thereferencevariablereferstotheobjectallocatedintheheapmemoryarea. Here,s1ands2botharereferencevariablesthatrefertotheobjectsallocatedinmemory. 3)ObjectandClassExample:Initializationthroughaconstructor WewilllearnaboutconstructorsinJavalater. ObjectandClassExample:Employee Let'sseeanexamplewherewearemaintainingrecordsofemployees. File:TestEmployee.java classEmployee{ intid; Stringname; floatsalary; voidinsert(inti,Stringn,floats){ id=i; name=n; salary=s; } voiddisplay(){System.out.println(id+""+name+""+salary);} } publicclassTestEmployee{ publicstaticvoidmain(String[]args){ Employeee1=newEmployee(); Employeee2=newEmployee(); Employeee3=newEmployee(); e1.insert(101,"ajeet",45000); e2.insert(102,"irfan",25000); e3.insert(103,"nakul",55000); e1.display(); e2.display(); e3.display(); } } TestitNow Output: 101ajeet45000.0 102irfan25000.0 103nakul55000.0 ObjectandClassExample:Rectangle ThereisgivenanotherexamplethatmaintainstherecordsofRectangleclass. File:TestRectangle1.java classRectangle{ intlength; intwidth; voidinsert(intl,intw){ length=l; width=w; } voidcalculateArea(){System.out.println(length*width);} } classTestRectangle1{ publicstaticvoidmain(Stringargs[]){ Rectangler1=newRectangle(); Rectangler2=newRectangle(); r1.insert(11,5); r2.insert(3,15); r1.calculateArea(); r2.calculateArea(); } } TestitNow Output: 55 45 WhatarethedifferentwaystocreateanobjectinJava? Therearemanywaystocreateanobjectinjava.Theyare: Bynewkeyword BynewInstance()method Byclone()method Bydeserialization Byfactorymethodetc. Wewilllearnthesewaystocreateobjectlater. Anonymousobject Anonymoussimplymeansnameless.Anobjectwhichhasnoreferenceisknownasananonymousobject.Itcanbeusedatthetimeofobjectcreationonly. Ifyouhavetouseanobjectonlyonce,ananonymousobjectisagoodapproach.Forexample: newCalculation();//anonymousobject Callingmethodthroughareference: Calculationc=newCalculation(); c.fact(5); Callingmethodthroughananonymousobject newCalculation().fact(5); Let'sseethefullexampleofananonymousobjectinJava. classCalculation{ voidfact(intn){ intfact=1; for(inti=1;i<=n;i++){ fact=fact*i; } System.out.println("factorialis"+fact); } publicstaticvoidmain(Stringargs[]){ newCalculation().fact(5);//callingmethodwithanonymousobject } } Output: Factorialis120 Creatingmultipleobjectsbyonetypeonly Wecancreatemultipleobjectsbyonetypeonlyaswedoincaseofprimitives. Initializationofprimitivevariables: inta=10,b=20; Initializationofreferncevariables: Rectangler1=newRectangle(),r2=newRectangle();//creatingtwoobjects Let'sseetheexample: //JavaProgramtoillustratetheuseofRectangleclasswhich //haslengthandwidthdatamembers classRectangle{ intlength; intwidth; voidinsert(intl,intw){ length=l; width=w; } voidcalculateArea(){System.out.println(length*width);} } classTestRectangle2{ publicstaticvoidmain(Stringargs[]){ Rectangler1=newRectangle(),r2=newRectangle();//creatingtwoobjects r1.insert(11,5); r2.insert(3,15); r1.calculateArea(); r2.calculateArea(); } } TestitNow Output: 55 45 RealWorldExample:Account File:TestAccount.java //JavaProgramtodemonstratetheworkingofabanking-system //wherewedepositandwithdrawamountfromouraccount. //CreatinganAccountclasswhichhasdeposit()andwithdraw()methods classAccount{ intacc_no; Stringname; floatamount; //Methodtoinitializeobject voidinsert(inta,Stringn,floatamt){ acc_no=a; name=n; amount=amt; } //depositmethod voiddeposit(floatamt){ amount=amount+amt; System.out.println(amt+"deposited"); } //withdrawmethod voidwithdraw(floatamt){ if(amount TestitNow Output: 832345Ankit1000.0 Balanceis:1000.0 40000.0deposited Balanceis:41000.0 15000.0withdrawn Balanceis:26000.0 NextTopicConstructorinjava ←prev next→ ForVideosJoinOurYoutubeChannel:JoinNow Feedback SendyourFeedbackto[email protected] HelpOthers,PleaseShare LearnLatestTutorials Splunk SPSS Swagger Transact-SQL Tumblr ReactJS Regex ReinforcementLearning RProgramming RxJS ReactNative PythonDesignPatterns PythonPillow PythonTurtle Keras Preparation Aptitude Reasoning VerbalAbility InterviewQuestions CompanyQuestions TrendingTechnologies ArtificialIntelligence AWS Selenium CloudComputing Hadoop ReactJS DataScience Angular7 Blockchain Git MachineLearning DevOps B.Tech/MCA DBMS DataStructures DAA OperatingSystem ComputerNetwork CompilerDesign ComputerOrganization DiscreteMathematics EthicalHacking ComputerGraphics SoftwareEngineering WebTechnology CyberSecurity Automata CProgramming C++ Java .Net Python Programs ControlSystem DataMining DataWarehouse JavatpointServicesJavaTpointofferstoomanyhighqualityservices.Mailuson[email protected],togetmoreinformationaboutgivenservices.WebsiteDesigningWebsiteDevelopmentJavaDevelopmentPHPDevelopmentWordPressGraphicDesigningLogoDigitalMarketingOnPageandOffPageSEOPPCContentDevelopmentCorporateTrainingClassroomandOnlineTrainingDataEntryTrainingForCollegeCampusJavaTpointofferscollegecampustrainingonCoreJava,AdvanceJava,.Net,Android,Hadoop,PHP,WebTechnologyandPython.Pleasemailyourrequirementat[email protected]Duration:1weekto2weekLike/Subscribeusforlatestupdatesornewsletter



請為這篇文章評分?