lecture 2 classes i
TRANSCRIPT
- 1. Introduction to Computer Science II COSC 1320/6305 Lecture2:Defining Classes I (Chapter 4)
2. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 3. Class Participation NetBeans Projects 4. http://wps.aw.com/aw_savitch_abjava_4s/110/28360/7260312.cw/index.html 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 5. http://wps.aw.com/aw_savitch_abjava_4s/110/28360/7260312.cw/index.html 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 6. Class Participation NetBeans Projects 7. ClassesandObjectsin Java Basics ofClassesinJava 8. Contents
- Introduce toclassesandobjectsinJava .
- Understand how some of the OO concepts learnt so far are supported in Java.
- Understand important features in Javaclasses .
9. Introduction
- Java is a true OO language and therefore the underlying structure of all Java programs isclasses .
- Anything we wish to represent in Java must be encapsulated in aclassthat defines the state and behaviour of the basic program components known asobjects .
- Classescreateobjectsandobjectsusemethodsto communicate between them. They provide a convenient method forpackaging a group of logically related data itemsandfunctions that work on them .
- Aclassessentiallyserves as a templatefor anobjectand behaves like a basic data type int. It is therefore important to understand how thefieldsandmethodsare defined in a class and how they are used to build a Java program that incorporates the basic OO concepts such asencapsulation ,inheritance , andpolymorphism .
10. Classes
- Aclass is a collection offields(data) andmethods (procedure or function) that operate on that data.
Circle centre radius circumference() area() 11. Classes
- Aclass is a collection offields (data) andmethods (procedure or function) that operate on that data.
- The basic syntax for aclassdefinition:
- Bare bone class no fields ,no methods
publicclassCircle{ // my circle class }
-
- class ClassName[ extendsSuperClassName ]
-
- {
-
-
- [ fields declaration ]
-
-
-
- [ methods declaration ]
-
- }
12. Adding Fields:ClassCirclewith fields
- Addfields
- Thefields(data) are also called theinstancevariables .
public classCircle { publicdouble x ,y ;// center coordinate publicdouble r ;//radius of the circle } 13. AddingMethods
- Aclasswith only data fields has nolife .Objectscreated by such a classcannot respond to any messages .
- Methodsare declared inside the body of the class but immediately after the declaration ofdata fields .
- The general form of amethod declarationis:
typeMethodName(parameter-list) { Method-body; } 14. AddingMethodstoClassCircle publicclassCircle { publicdouble x, y;// centre of the circle publicdouble r;// radius of circle //Methods to return circumference and area publicdouble circumference () {return 2*3.14*r; } publicdouble area () {return 3.14 * r * r;} } Method Body publiconly for example purposes!!!! 15. Data Abstraction
- Declare theCircle class , have created a new data type Data Abstraction
- Can define variables ( objects ) of that type:
-
-
- CircleaCircle ;
-
-
-
- CirclebCircle ;
-
16. Class of Circle
- aCircle ,bCirclesimply refers to a Circleobject ,not an object itself .
aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null null
-
-
- CircleaCircle ;
-
-
-
- CirclebCircle ;
-
17. Creatingobjectsof a class
- Objectsare created dynamically using thenewkeyword.
- aCircleandbCirclerefer toCircle objects
bCircle=new Circle(); aCircle=new Circle(); 18. Creatingobjectsof a class aCircle=new Circle() ; bCircle=new Circle() ; bCircle = aCircle ; 19. Creatingobjectsof a class Q bCircle Before Assignment Q bCircle After Assignment aCircle=new Circle() ; bCircle=new Circle() ; bCircle = aCircle ; P aCircle P aCircle 20. Automatic garbage collection
- Theobjectdoesnot have a referenceand cannot be used in future.
- Theobjectbecomes a candidate for automaticgarbage collection .
- Java automatically collects garbage periodicallyand releases the memory used to be used inthe future.
Q 21. AccessingObject /CircleData
- Similar toCsyntax for accessing data defined in a structure.
CircleaCircle=new Circle() ; aCircle . x= 2.0;// initialize center and radius aCircle . y= 2.0; aCircle . r= 1.0; ObjectName . V ariableName ObjectName . MethodName (parameter-list) 22. ExecutingMethodsin Object/Circle
- UsingObjectMethods :
CircleaCircle=new Circle() ; double area;aCircle . r =1.0; area = aCircle . area (); sent message toaCircle 23. Using Circle Class
- // Circle.java:Contains both Circle class and its user class
- //Add Circle class code here
- classMyMain
- {
- public staticvoid main(String args[])
- {
- CircleaCircle ;// creating reference
- aCircle= newCircle() ;// creating object
- aCircle . x = 10;// assigning value to data field
- aCircle . y = 20;
- aCircle . r = 5;
- double area =aCircle . area() ; // invoking method
- double circumf =aCircle . circumference ();
- System.out.println("Radius="+ aCircle . r+" Area="+area);
- System.out.println("Radius="+ aCircle .r+" Circumference ="+circumf);
- }
- }
Radius=5.0 Area=78.5 Radius=5.0 Circumference =31.400000000000002 24. Summary
- Classes,objects , andmethodsare the basic components used in Java programming.
- We have discussed:
-
- How to define aclass
-
- How to createobjects
-
- How toadd data fieldsandmethodsto classes
-
- How toaccess data fieldsandmethodsto classes
25. Introduction
- Classesare the most important language feature that makeobject-oriented programming( OOP ) possible
- Programming inJavaconsists of defining a number ofclasses
-
- Every program is aclass
-
- All helping softwareconsists of classes
-
- All programmer-defined types areclasses
- Classesare central toJava
4- 26. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 27. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 28. Class Definitions
- You already know how to useclassesand theobjectscreated from them, and how toinvoke their methods
-
- For example, you have already been using the predefinedStringandScanner classes
- Now you will learn how to defineyour own classesand theirmethods , and how to createyour own objectsfrom them
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 29. AClassIs a Type
- Aclassis a special kind of programmer-defined type, and variables can be declared of aclasstype
- A value of aclasstype is called anobjectoran instance oftheclass
-
- If A is aclass , then the phrases " blais of type A," " blais anobjectof theclassA," and " blaisan instance oftheclassA" mean the same thing
- Aclassdetermines the types ofdatathat anobjectcan contain, as well as theactionsit can perform
4- CLASS Participation A! 30. UML Class Diagram 4- 31. File Names and Locations
- Reminder:aJava filemust be given the same name as theclassit contains with an added.javaat the end
-
- For example, aclassnamedMyClassmust be in a file namedMyClass.java
- For now, your program and all theclassesit uses should be in the same directory or folder
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 32. Java Application Programs
- AJavaapplication programor "regular"Java programis aclasswith amethod namedmain
-
- When aJava application programis run, therun-time systemautomatically invokes themethodnamedmain
-
- AllJava application programsstart with themain method
1- Copyright 2010 Pearson Addison-Wesley. All rights reserved. CLASS Participation B! (pp. 6) 33. A SampleJava Application Program 1- 34. System .out. println
- Java programswork by having things calledobjectsperformactions
-
- System.out :anobjectused forsending outputto the screen
- Theactionsperformed by anobjectare calledmethods
-
- println :themethodoractionthat theSystem.out objectperforms
1- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 35. System .out. println
- Invokingorcallingamethod :When anobjectperforms anactionusing amethod
-
- Also calledsending a message to theobject
-
- Methodinvocation syntax (in order):anobject , a dot (period) , themethodname, and apair of parentheses
-
- Arguments :Zero or more pieces of information needed by themethodthat are placed inside the parentheses
System .out. println ("This is an argument"); 1- 36. Variabledeclarations
- Variabledeclarations inJavaare similar to those in other programming languages (C)
-
- Simply give thetypeof thevariablefollowed by its name and a semicolon;
- intanswer ;
1- 37. Using=and+
- InJava , the equal sign ( = ) is used as theassignment operator
-
- Thev ariableon the left side of the assignment operator=isassigned the valueof the expression on the right side of the assignment operator=
-
- answer=2+2;
- InJava , the plus sign ( + ) can be used to denote addition (as above) orconcatenation
-
- Using+ ,two strings can be connected together
System.out.println("2 plus 2 is "+answer); 1- 38. Primitive Type Valuesvs. ClassType Values
- A primitive type value is a single piece ofdata
- Aclasstype value orobjectcan have multiple pieces ofdata , as well as actions calledmethods
-
- Allobjectsof aclasshave the samemethods
-
- Allobjectsof aclasshave thesame pieces of data(i.e., name, type, and number)
-
- For a givenobject ,each piece of datacan hold a different value
4- CLASS Participation C! (pp. 188) 39. UML Class Diagram 4- 40. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 41. A Formal Parameter Used as aLocal Variable( BillingDialog.java ) 4- 42. ThenewOperator
- Anobjectof aclassis named or declared by avariableof theclasstype:
-
- ClassNameclassVar ;
- Thenewoperator must then be used to create theobjectand associate it with itsvariablename:
-
- classVar=newClassName();
- These can be combined as follows:
-
- ClassNameclassVar=newClassName();
4- 43. Step Into 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 44. The Contents of aClassDefinition
- Aclassdefinition specifies thedata itemsandmethodsthat all of itsobjectswill have
- Thesedata itemsandmethodsare sometimes calledmembersof theobject
- Data itemsare calledfieldsorinstance variables
- Instance variable declarationsandmethod definitionscan be placed in any order within theclassdefinition
4- 45. ( Bill.java ) 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. The Contents of aClassDefinition 46. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 47. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 48. ( BillingDialog.java ) 4- 49. Instance Variables
- Instance variablescan be defined as in the following two examples
-
- Note thepublicmodifier (for now):
-
- publicString instanceVar1 ;
-
- public int instanceVar2 ;
- In order to refer to a particularinstance variable , preface it with itsobjectname as follows:
-
- objectName . instanceVar1
-
- objectName . instanceVar2
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 50.
- Methoddefinitions are divided into two parts:aheadingand abody :
-
- public voidmyMethod()Heading
-
- {
-
- codeto perform some actionBody
-
- and/or compute a value
-
- }
- Methodsare invoked using the name of the callingobjectand themethodname as follows:
-
- classVar . myMethod() ;
- Invoking amethodis equivalent to executing themethodbody
Methods 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 51. ( BillingDialog.java ) 4- 52. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 53. More AboutMethods
- There are two kinds ofmethods :
-
- Methodsthat compute and return a value
-
- Methodsthat perform an action
-
-
- This type ofmethod does not return a value, and is called avoid method
-
- Each type ofmethoddiffers slightly in how it is defined as well as how it is (usually) invoked
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 54. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 55. More AboutMethods
- Amethodthat returns a value must specify thetype of that valuein its heading:
- publictypeReturnedmethodName (paramList)
- Avoid methoduses the keywordvoidin its heading to show that it does not return a value :
- public void methodName (paramList)
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 56. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 57. mainis avoid Method
- Aprogram in Javais just a class that has amain method
- When you give a command to run aJava program , the run-time system invokes themethod main
- Note thatmainis avoid method , as indicated by its heading:
-
- public static voidmain (String[] args)
58. returnStatements
- The body of both types ofmethodscontains a list of declarations and statements enclosed in a pair of braces
-
- public< voidortypeReturned >myMethod ()
-
- {
-
- declarationsBody
-
- statements
-
- }
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 59. returnStatements
- The body of amethodthat returns a value must also contain one or morereturnstatements
-
- Areturnstatement specifies the value returned and ends themethodinvocation:
-
- return Expression;
-
- Expressioncan be any expression that evaluates to something of the type returned listed in themethodheading
4- 60. returnStatements
- Avoid methodneed not contain areturnstatement, unless there is a situation that requires the method to end before all its code is executed
- In this context, since it does not return a value, areturnstatement is used without an expression:
-
- return;
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 61. MethodDefinitions
- An invocation of amethodthat returns a value can be used as an expression anyplace that a value of thetypeReturnedcan be used:
-
- typeReturned tRVariable;
-
- tRVariable= objectName . methodName() ;
- An invocation of avoid methodis simply a statement:
-
- objectName . methodName() ;
4- 62. AnyMethodCan Be Used As avoid Method
- Amethodthat returns a value can also perform an action
- If you want the action performed, but do not need the returned value, you can invoke themethodas if it were avoid method , and the returned value will be discarded:
-
- objectName . returnedValueMethod() ;
4- 63. Local Variables
- A variable declared within amethoddefinition is called alocal variable
-
- All variables declared in themain methodarelocal variables
-
- Allmethodparameters arelocal variables
- If twomethodseach have alocal variableof the same name, they are stilltwo entirely different variables
4- 64. Global Variables
- Some programming languages include another kind of variable called aglobalvariable
- TheJava languagedoesnothave global variables
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 65. Blocks
- Ablockis another name for a compound statement, that is, a set of Java statements enclosed in braces, {}
- Avariabledeclared within a block islocalto that block, and cannot be used outside the block
- Once a variable has been declared within a block, its name cannot be used for anything else within the samemethoddefinition
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 66. Declaring Variables in aforStatement
- You candeclare one or more variableswithin the initialization portion of aforstatement
- Avariableso declared will be local to theforloop, and cannot be used outside of the loop
- If you need to use such a variable outside of a loop, then declare it outside the loop
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 67. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 68. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 69. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 70. ( Bill.java ) 4- 71. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 72. Parametersof a Primitive Type
- Themethodsseen so far have had no parameters, indicated by an empty set of parentheses in themethodheading
- Somemethodsneed to receive additional data via a list ofparametersin order to perform their work
-
- Theseparametersare also calledformal parameters
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 73. Parameters of a Primitive Type
- Aparameter listprovides a description of the data required by amethod
-
- It indicates the number and types of data pieces needed, the order in which they must be given, and the local name for these pieces as used in themethod
- publicdoublemyMethod (int p1, int p2, double p3)
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 74. Parameters of a Primitive Type
- When amethodis invoked, the appropriate values must be passed to themethodin the form ofarguments
-
- Arguments are also calledactual parameters
- The number and order of the arguments must exactly match that of the parameter list
- The type of each argument must be compatible with the type of the corresponding parameter
-
- int a=1,b=2,c=3;
-
- double result= myMethod(a,b,c) ;
4- 75. Parameters of aPrimitive Type
- In the preceding example,the value of each argument(not the variable name) is plugged into the correspondingmethodparameter
-
- This method of plugging in arguments for formal parameters is known as thecall-by-value mechanism
4- 76. Parameters of a Primitive Type
- If argument and parameter types do not match exactly,Java will attempt to make an automatic type conversion
-
- In the preceding example, theintvalue of argumentcwould becastto adouble
-
- A primitive argument can be automaticallytype castfrom any of the following types, to any of the types that appear to its right:
-
- byte short int long float double
-
- char
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 77. Parameters of a Primitive Type
- A parameter is often thought of as a blank orplaceholderthat is filled in by the value of its corresponding argument
- However, a parameter is more than that:it is actually alocal variable
- When amethodis invoked, the value of its argument is computed, and the corresponding parameter (i.e.,local variable ) is initialized to this value
- Even if the value of aformal parameteris changed within amethod(i.e., it is used as alocal variable ) the value of the argument cannot be changed
4- 78. AFormal ParameterUsed as aLocal Variable( Bill.java ) 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 79. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 80. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 81. 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 82. Pitfall:Use of the Terms " Parameter " and " Argument "
- Do not be surprised to find that people often use the termsparameterandargumentinterchangeably
- When you see these terms, you may have to determine their exact meaning from context
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 83. ThethisParameter
- Allinstance variablesare understood to have
- < the calling object > .in front of them
- If an explicit name for thecalling objectis needed, the keywordthiscan be used
-
- myInstanceVariable always means and is always interchangeable withthis . myInstanceVariable
4- 84. Thethis Parameter
- this mustbe used if aparameteror otherlocal variablewith the same name is used in themethod
-
- Otherwise, allinstances of the variable namewill be interpreted aslocal
-
- int someVariable =this . someVariable
local instance 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 85. ThethisParameter
- Thethis parameter is a kind ofhidden parameter
- Even though it does not appear on theparameter listof amethod , it is still aparameter
- When amethodis invoked, thecalling objectis automatically plugged in forthis
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 86. AFormal ParameterUsed as aLocal Variable( Bill.java ) 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 87. AFormal ParameterUsed as aLocal Variable4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 88. MethodsThat Return a Boolean Value
- An invocation of amethodthat returns a value of typebooleanreturns eithertrueorfalse
- Therefore, it is common practice to use an invocation of such amethodto control statements and loops where a Boolean expression is expected
-
- if-elsestatements,whileloops, etc.
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 89. Themethods equalsandtoString
- Java expects certainmethods , such asequals andtoString , to be in all, or almost all,classes
- The purpose ofequals , abooleanvaluedmethod , is to compare twoobjectsof theclassto see if they satisfy the notion of "being equal
-
- Note:You cannot use==to compareobjects
-
- publicbooleanequals (ClassNameobjectName )
- The purpose of thetoString methodis to return aStringvalue that represents the data in theobject
-
- publicStringtoString()
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 90. TestingMethods
- Eachmethodshould be tested in aprogramin which it is the only untested program
-
- A program whose only purpose is to testa methodis calledadriver program
- Onemethodoften invokes othermethods , so one way to do this is to first test all the methods invoked by thatmethod , and then test themethoditself
-
- This iscalledbottom-up testing
- Sometimes it is necessary to test amethodbefore anothermethodit depends on is finished or tested
-
- In this case, use a simplified version of themethod , called astub ,to return a value for testing
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 91. The Fundamental Rule for TestingMethods
- Everymethodshould be tested in a program in which every othermethodin the testing program has already been fully tested and debugged
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 92. Information Hidingand Encapsulation
- Information hiding is the practice of separating how to use aclassfrom the details of its implementation
-
- Abstractionis another term used to express the concept of discarding details in order to avoid information overload
- Encapsulation means that thedataandmethodsof a class are combined into a single unit (i.e., a classobject ), which hides the implementation details
-
- Knowing the details is unnecessary because interaction with theobjectoccurs via a well-defined and simpleinterface
-
- InJava , hiding details is done by marking themprivate
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 93. Encapsulation 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 94. A Couple of Important Acronyms:API and ADT
- The API ora pplicationp rogrammingi nterfacefor aclassis a description of how to use theclass
-
- A programmer need only read theAPI in order to use a well designedclass
- AnADTorabstract data type is a data type that is written using good information-hiding techniques
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 95. publicandprivateModifiers
- The modifierpublicmeans that there are no restrictions on where aninstance variableormethodcan be used
- The modifierprivatemeans that aninstance variableormethodcannot be accessed by name outside of theclass
- It is considered good programming practice to makeall instance variablesprivate
- Mostmethodsarepublic , and thus providecontrolled access to theobject
- Usually,methodsareprivateonly if used as helpingmethodsfor othermethodsin the class
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 96. Accessor and MutatorMethods
- Accessor methodsallow the programmer to obtain the value of anobject 'sinstance variables
-
- Thedatacan be accessed but not changed
-
- The name of an accessormethodtypically starts with the wordget
- Mutator methodsallow the programmer to change the value of anobject 'sinstance variablesin a controlled manner
-
- Incomingdatais typically tested and/or filtered
-
- The name of a mutatormethodtypically starts with the wordset
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 97. AClassHas Access toPrivateMembers of AllObjectsof theClass
- Within the definition of aclass ,privatemembers ofany objectof theclasscan be accessed, not justprivatemembers of the callingobject
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 98. Preconditions and Postconditions
- Thepreconditionof amethodstates what is assumed to be true when themethodis called
- Thepostconditionof amethodstates what will be true after themethodis executed, as long as the precondition holds
- It is a good practice to always think in terms of preconditions and postconditions when designing amethod , and when writing themethodcomment
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 99. Overloading
- Overloadingis when two or moremethods in the sameclasshave the samemethodname
- To be valid, any two definitions of themethodname must have differentsignatures
-
- A signatureconsists of the name of amethodtogether with its parameter list
-
- Differing signaturesmust have different numbers and/or types of parameters
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 100. Overloadingand Automatic Type Conversion
- IfJavacannot find amethod signaturethat exactly matches amethodinvocation, it will try to use automatic type conversion
- The interaction ofoverloadingand automatic type conversion can have unintended results
- In some cases ofoverloading , because of automatic type conversion, a singlemethodinvocation can be resolved in multiple ways
-
- Ambiguousmethodinvocations will produce an error in Java
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 101. Pitfall:You Can NotOverloadBased on the Type Returned
- The signatureof amethodonly includes themethodname and its parameter types
-
- The signaturedoesnotinclude the type returned
- Javadoes not permitmethodswith the same name and different return typesin the sameclass
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 102. You Can NotOverload Operatorsin Java
- Although many programming languages, such asC++ , allow you tooverload operators( + ,- , etc.),Javadoes not permit this
-
- You may only use amethodname and ordinarymethodsyntax to carry out the operations you desire
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 103. Constructors
- Aconstructoris a special kind ofmethodthat is designed to initialize theinstance variablesfor anobject :
-
- publicClassName (anyParameters)
-
- {
-
- Code
-
- }
-
- Aconstructormust have the same name as theclass
-
- Aconstructorhas no type returned, not evenvoid
-
- Constructorsare typically overloaded
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 104. Constructors
- Aconstructoris called when anobjectof the class is created usingnew
-
- ClassNameobjectName=new ClassName (anyArgs);
-
- Thename of the constructorand its parenthesized list of arguments (if any) must follow thenewoperator
-
- This is theonlyvalid way to invoke aconstructor :a constructorcannot beinvoked like anordinary method
- If aconstructoris invoked again (usingnew ), thefirst objectis discarded and an entirelynew objectis created
-
- If you need tochange the values of instance variablesof theobject , usemutator methodsinstead
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 105. You Can InvokeAnother Methodin aConstructor
- The first action taken by aconstructoris to create anobjectwithinstance variables
- Therefore, it is legal to invokeanother methodwithin the definition of aconstructor , since it has the newly createdobjectas itscalling object
-
- For example,mutator methodscan be used to set the values of theinstance variables
-
- It is even possible forone constructorto invokeanother
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 106. AConstructorHas athisParameter
- Like any ordinarymethod , everyconstructorhas athis parameter
- Thethisparameter can be used explicitly, but is more often understood to be there than written down
- The first action taken by aconstructoris to automatically create anobjectwithinstance variables
- Then within the definition of aconstructor , thethisparameter refers to theobjectcreated by theconstructor
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 107. Include a No-ArgumentConstructor
- If youdo not include any constructorsin yourclass ,Javawill automatically create adefaultorno-argumentconstructorthat takes no arguments, performs no initializations, but allows theobjectto be created
- If you include even one constructorin yourclass ,Java will not providethisdefault constructor
- If you includeany constructorsin yourclass , be sure to provide yourown no-argument constructoras well
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 108. Default Variable Initializations
- Instance variablesare automatically initialized inJava
-
- booleantypes are initialized to false
-
- Other primitives are initialized to the zero of their type
-
- Classtypes are initialized tonull
- However, it is a better practice to explicitly initializeinstance variablesin aconstructor
- Note:Local variablesare not automatically initialized
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 109. TheStringTokenizer Class
- TheStringTokenizer classis used torecover the wordsor tokensin a multi-wordString
-
- You can use whitespace characters to separate each token, or you can specify the characters you wish to use as separators
-
- In order to use theStringTokenizer class , be sure to include the following at the start of the file:
-
- importjava.util.StringTokenizer;
4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 110. SomeMethodsin theStringTokenizerClass (Part 1 of 2) 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved. 111. SomeMethodsin theStringTokenizerClass (Part 2 of 2) 4- Copyright 2010 Pearson Addison-Wesley. All rights reserved.