Java Constructors - W3Schools
文章推薦指數: 80 %
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. Tutorials References Exercises Videos ProNEW Menu Login PaidCourses WebsiteNEW HTML CSS JAVASCRIPT SQL PYTHON PHP BOOTSTRAP HOWTO W3.CSS JAVA JQUERY C++ C# R React Kotlin 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 ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility 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 Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz SQLQuiz MySQLQuiz PHPQuiz PythonQuiz NumPyQuiz PandasQuiz SciPyQuiz jQueryQuiz JavaQuiz C++Quiz C#Quiz RQuiz XMLQuiz CyberSecurityQuiz BootstrapQuiz Bootstrap4Quiz Bootstrap5Quiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse SQLCourse PHPCourse PythonCourse NumPyCourse PandasCourse DataAnalyticsCourse jQueryCourse JavaCourse C++Course C#Course RCourse XMLCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate SQLCertificate PHPCertificate PythonCertificate DataScienceCertificate Bootstrap3Certificate Bootstrap4Certificate jQueryCertificate JavaCertificate C++Certificate ReactCertificate XMLCertificate × Tutorials References Exercises PaidCourses Spaces Videos Shop Pro JavaTutorial JavaHOME JavaIntro JavaGetStarted JavaSyntax JavaComments JavaVariables Variables PrintVariables DeclareMultipleVariables Identifiers JavaDataTypes DataTypes Numbers Booleans Characters Non-primitiveTypes JavaTypeCasting JavaOperators JavaStrings Strings 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 JavaConstructors ❮Previous Next❯ JavaConstructors AconstructorinJavaisaspecialmethodthatisusedtoinitializeobjects. Theconstructoriscalledwhenanobjectofaclassiscreated.Itcanbeusedto setinitialvaluesforobjectattributes: Example Createaconstructor: //CreateaMainclass publicclassMain{ intx; //Createaclassattribute //CreateaclassconstructorfortheMainclass publicMain(){ x=5; //Settheinitialvaluefortheclassattributex } publicstaticvoidmain(String[]args){ MainmyObj=newMain();//CreateanobjectofclassMain(Thiswillcalltheconstructor) System.out.println(myObj.x);//Printthevalueofx } } //Outputs5 TryitYourself» Notethattheconstructornamemustmatchtheclassname,anditcannothavea returntype(likevoid). Alsonotethattheconstructoriscalledwhentheobjectiscreated. Allclasseshaveconstructorsbydefault:ifyoudonotcreateaclassconstructor yourself,Javacreatesoneforyou.However,thenyouarenotabletosetinitialvaluesforobjectattributes. ConstructorParameters Constructorscanalsotakeparameters,whichisusedtoinitialize attributes. Thefollowingexampleaddsanintyparameter totheconstructor. Insidetheconstructorwesetxtoy(x=y).Whenwecall theconstructor,wepassaparametertotheconstructor(5),whichwillsetthevalueof xto5: Example publicclassMain{ intx; publicMain(inty){ x=y; } publicstaticvoidmain(String[]args){ MainmyObj=newMain(5); System.out.println(myObj.x); } } //Outputs5 TryitYourself» Youcanhaveasmanyparametersasyouwant: Example publicclassMain{ intmodelYear; StringmodelName; publicMain(intyear,Stringname){ modelYear=year; modelName=name; } publicstaticvoidmain(String[]args){ MainmyCar=newMain(1969,"Mustang"); System.out.println(myCar.modelYear+""+myCar.modelName); } } //Outputs1969Mustang TryitYourself» ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame
延伸文章資訊
- 1Java Gossip: 建構方法(Constructor) - OpenHome.cc
下面這個程式示範如何使用自訂的安全陣列類別:. UseConstructor.java. public class UseConstructor { public static void mai...
- 2Java - Constructors - Tutorialspoint
Java - Constructors ... A constructor initializes an object when it is created. It has the same n...
- 3Java Constructor 建構子方法的使用 - Java程式教學甘仔店
Java Constructor 建構子方法的使用. 前言: 本文相關用詞類別物件(class) 方法(method) 參數(parameter) 回傳值(return value)
- 4Java Constructors (With Examples) - Programiz
- 5Java Constructors (With Examples) - Programiz
A constructor in Java is similar to a method that is invoked when an object of the class is creat...