Java Classes and Objects - W3Schools
文章推薦指數: 80 %
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
延伸文章資訊
- 1java中public class與class的區別詳解 - 程式前沿
如果一個類宣告的時候使用了public class進行了宣告,則類名稱必須與檔名稱完全一致。 範例:定義一個類(檔名稱為:Hello.java) 複製程式碼程式碼如下:
- 2Java :: public/建構式/重載
package cc.openhome.virtual; public class CashCard { ...略 public CashCard(String number, int bala...
- 3JAVA的封裝 - iT 邦幫忙::一起幫忙解決難題,拯救IT 人的一天
從以上的敘述,讀者可以推知這四種存取範圍的大小是public > protected > package > private。 Package的定義所謂package,可以想成是在設計或實作上相...
- 4public class與class的區別 - 程式人生
public class與class的區別; 一個java原始檔中可以定義多個class,; 一個Java原始檔中可以沒有public class,有且只有一個。(類體,之中不能直接寫java語...
- 5定義類別(Class) | Java SE 6 技術手冊 - caterpillar
範例7.1 Account.java. public class Account { private String accountNumber; private double balance; ...