Java Classes and Objects - W3Schools

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

Create a class named " Main " with a variable x: public class Main { int x = 5; }. Remember from the Java Syntax chapter that a class should always start ... Tutorials References Exercises Videos Menu Login FreeWebsite GetCertified Pro HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP BOOTSTRAP HOWTO W3.CSS C C++ C# REACT R JQUERY DJANGO TYPESCRIPT NODEJS MYSQL    Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo LearnDjango LearnTypeScript ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility Blog DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises SQLExercises MySQLExercises PHPExercises PythonExercises NumPyExercises PandasExercises SciPyExercises jQueryExercises JavaExercises C++Exercises C#Exercises RExercises KotlinExercises GoExercises BootstrapExercises Bootstrap4Exercises Bootstrap5Exercises GitExercises ExcelExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz SQLQuiz MySQLQuiz PHPQuiz PythonQuiz NumPyQuiz PandasQuiz SciPyQuiz jQueryQuiz JavaQuiz C++Quiz C#Quiz RQuiz KotlinQuiz XMLQuiz BootstrapQuiz Bootstrap4Quiz Bootstrap5Quiz CyberSecurityQuiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse SQLCourse PHPCourse PythonCourse NumPyCourse PandasCourse DataAnalyticsCourse jQueryCourse JavaCourse C++Course C#Course RCourse React.jsCourse Bootstrap3Course Bootstrap4Course XMLCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate SQLCertificate PHPCertificate PythonCertificate DataScienceCertificate Bootstrap3Certificate Bootstrap4Certificate Bootstrap5Certificate jQueryCertificate JavaCertificate C++Certificate C#Certificate React.jsCertificate TypeScriptCertificate XMLCertificate CyberSecurityCertificate AccessibilityCertificate ExcelCertificate × Tutorials References Exercises GetCertified Spaces Videos Shop Pro JavaTutorial JavaHOME JavaIntro JavaGetStarted JavaSyntax JavaOutput JavaComments JavaVariables Variables PrintVariables DeclareMultipleVariables Identifiers JavaDataTypes DataTypes Numbers Booleans Characters Non-primitiveTypes JavaTypeCasting JavaOperators JavaStrings Strings Concatenation NumbersandStrings SpecialCharacters JavaMath JavaBooleans JavaIf...Else If...Else ShortHandIf...Else JavaSwitch JavaWhileLoop JavaForLoop ForLoop For-EachLoop JavaBreak/Continue JavaArrays Arrays LoopThroughanArray MultidimensionalArrays JavaMethods JavaMethods JavaMethodParameters JavaMethodOverloading JavaScope JavaRecursion JavaClasses JavaOOP JavaClasses/Objects JavaClassAttributes JavaClassMethods JavaConstructors JavaModifiers JavaEncapsulation JavaPackages/API JavaInheritance JavaPolymorphism JavaInnerClasses JavaAbstraction JavaInterface JavaEnums JavaUserInput JavaDate JavaArrayList JavaLinkedList JavaHashMap JavaHashSet JavaIterator JavaWrapperClasses JavaExceptions JavaRegEx JavaThreads JavaLambda JavaFileHandling JavaFiles JavaCreate/WriteFiles JavaReadFiles JavaDeleteFiles JavaHowTo AddTwoNumbers JavaReference JavaKeywords abstract boolean break byte case catch char class continue default do double else enum extends final finally float for if implements import instanceof int interface long new package private protected public return short static super switch this throw throws try void while JavaStringMethods JavaMathMethods JavaExamples JavaExamples JavaCompiler JavaExercises JavaQuiz JavaCertificate JavaClassesandObjects ❮Previous Next❯ JavaClasses/Objects Javaisanobject-orientedprogramminglanguage. EverythinginJavaisassociatedwithclassesandobjects,alongwithitsattributesand methods.Forexample:inreallife,acarisanobject.Thecarhasattributes,suchasweightandcolor,and methods,suchasdriveandbrake. AClassislikeanobjectconstructor,ora"blueprint"forcreatingobjects. CreateaClass Tocreateaclass,usethekeywordclass: Main.java Createaclassnamed"Main"witha variablex: publicclassMain{  intx=5; } RememberfromtheJavaSyntaxchapterthataclassshouldalwaysstartwithanuppercasefirstletter,andthatthenameofthejavafileshouldmatchtheclassname. CreateanObject InJava,anobjectiscreatedfromaclass.Wehavealreadycreatedtheclassnamed Main, sonowwecanusethistocreateobjects. TocreateanobjectofMain, specifytheclassname,followedbytheobjectname,andusethekeywordnew: Example Createanobjectcalled"myObj"andprintthevalueofx: publicclassMain{  intx=5;  publicstaticvoidmain(String[]args){    MainmyObj=newMain();    System.out.println(myObj.x);  } } TryitYourself» MultipleObjects Youcancreatemultipleobjectsofoneclass: Example CreatetwoobjectsofMain: publicclassMain{  intx=5;  publicstaticvoidmain(String[]args){    MainmyObj1=newMain(); //Object1    MainmyObj2=newMain(); //Object2    System.out.println(myObj1.x);    System.out.println(myObj2.x);  } } TryitYourself» UsingMultipleClasses Youcanalsocreateanobjectofaclassandaccessitinanotherclass.This isoftenusedforbetterorganizationofclasses(oneclasshasallthe attributesandmethods,whiletheotherclassholdsthemain()method(codeto beexecuted)). Rememberthatthenameofthejavafileshouldmatchtheclassname.Inthis example,wehavecreatedtwofilesinthesamedirectory/folder: Main.java Second.java Main.java publicclassMain{  intx=5; } Second.java classSecond{  publicstaticvoidmain(String[]args){    MainmyObj=newMain();    System.out.println(myObj.x);  } } Whenbothfileshavebeencompiled: C:\Users\YourName>javacMain.java C:\Users\YourName>javacSecond.java RuntheSecond.javafile: C:\Users\YourName>javaSecond Andtheoutputwillbe: 5 TryitYourself» Youwilllearnmuchmoreaboutclassesandobjectsinthenextchapters. TestYourselfWithExercises Exercise: CreateanobjectofMyClasscalledmyObj. =new(); SubmitAnswer» StarttheExercise ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame



請為這篇文章評分?