lecture 4 b writing classes b class declarations b method declarations b constructors b instance...
DESCRIPTION
Classes: Create your own b A class contains data declarations and method declarations int x, y; char ch; Data declarations Method declarationsTRANSCRIPT
Lecture 4Lecture 4
Writing ClassesWriting Classes class declarationsclass declarations method declarationsmethod declarations constructorsconstructors instance variablesinstance variables encapsulationencapsulation method overloadingmethod overloading program developmentprogram development
2
ObjectsObjects An object has:An object has:
• statestate - descriptive characteristics - descriptive characteristics• behaviorsbehaviors - what it can do (or be done to it) - what it can do (or be done to it)
Example: Example: StringString • statestate - characters comprising the string - characters comprising the string• behaviorsbehaviors - services, such as - services, such as toUpperCasetoUpperCase
Example: Example: coincoin • statestate - "heads" or "tails” - "heads" or "tails”• behaviorsbehaviors - “flip” (may change its state) - “flip” (may change its state)
A A classclass is a blueprint of an object is a blueprint of an object
Classes: Create your ownClasses: Create your own A class contains data declarations and method declarationsA class contains data declarations and method declarations
int x, y;char ch;
Data declarationsData declarations
Method declarationsMethod declarations
Classes: Brew your ownClasses: Brew your own The The scopescope of data is the area in a program in which that of data is the area in a program in which that
data can be used (referenced)data can be used (referenced)
int x, y;char ch;
Data declared at class level Data declared at class level can be used by all methods in classcan be used by all methods in class
Local data: Local data: - can only be used in these methods- can only be used in these methods
int x, y, z;char ch;
int x, w;
int z, y;char ch;
Writing MethodsWriting Methods A A method declarationmethod declaration specifies the code that will be specifies the code that will be
executed when the method is invoked (or called)executed when the method is invoked (or called)
When a method is invoked, the flow of control jumps to the When a method is invoked, the flow of control jumps to the method and executes its codemethod and executes its code
When complete, the flow returns to the place where the When complete, the flow returns to the place where the method was called and continuesmethod was called and continues
The invocation may or may not return a value, depending The invocation may or may not return a value, depending on how the method was definedon how the method was defined
myMethod();
myMethodcompute
Method Control FlowMethod Control Flow The called method could be within the same class, in which The called method could be within the same class, in which
case only the method name is neededcase only the method name is needed
doIt
helpMe
helpMe();
obj.doIt();
main
Method Control FlowMethod Control Flow The called method could be part of another class or objectThe called method could be part of another class or object
The Coin ClassThe Coin Class In our In our CoinCoin class we could define the following data: class we could define the following data:
• faceface, an integer that represents the current face, an integer that represents the current face• HEADSHEADS and and TAILSTAILS, integer constants that represent the , integer constants that represent the
two possible statestwo possible states
We might also define the following methods:We might also define the following methods:• a a CoinCoin constructor, to set up the object constructor, to set up the object• a a flipflip method, to flip the coin method, to flip the coin• a a getFacegetFace method, to return the current face method, to return the current face• a a toStringtoString method, to return a string for printing method, to return a string for printing
The Coin ClassThe Coin Class See See CountFlipsCountFlips.java.java (page 179)(page 179) See Coin.javaSee Coin.java (page 180)(page 180)
Once the Once the CoinCoin class has been defined, we can use it again class has been defined, we can use it again in other programs as neededin other programs as needed
Note that the Note that the CountFlipsCountFlips program did not use the program did not use the toStringtoString method method
A program will not necessarily use every service provided A program will not necessarily use every service provided by an objectby an object
Instance DataInstance Data The The faceface variable in the variable in the CoinCoin class is called class is called instance datainstance data
because each instance (object) of the because each instance (object) of the CoinCoin class has its own class has its own
A class declares the type of the data, but it does not reserve A class declares the type of the data, but it does not reserve any memory space for itany memory space for it
Every time a Every time a CoinCoin object is created, a new object is created, a new faceface variable is variable is created as wellcreated as well
The objects of a class share the method definitions, but they The objects of a class share the method definitions, but they have unique data spacehave unique data space
That's the only way two objects can have different statesThat's the only way two objects can have different states
Instance DataInstance Data See FlipRace.javaSee FlipRace.java (page 182)(page 182)
face 0
coin1
int face;
class Coin
face 1
coin2
12
EncapsulationEncapsulation You can take one of two views of an object:You can take one of two views of an object:
• internal - the structure of its data, the algorithms used by its methodsinternal - the structure of its data, the algorithms used by its methods
• external - the interaction of the object with other objects in the external - the interaction of the object with other objects in the programprogram
From the external view, an object is an From the external view, an object is an encapsulatedencapsulated entity, entity, providing a set of specific servicesproviding a set of specific services
Services define the Services define the interfaceinterface to the object to the object
Objects are thus Objects are thus abstractionsabstractions• hiding details from the rest of the systemhiding details from the rest of the system
13
EncapsulationEncapsulation An object should be An object should be self-governingself-governing
Any changes to the object's state (its variables) should be Any changes to the object's state (its variables) should be accomplished by that object's methodsaccomplished by that object's methods
We should make it difficult, if not impossible, for one We should make it difficult, if not impossible, for one object to "reach in" and alter another object's stateobject to "reach in" and alter another object's state
The user, or The user, or clientclient, of an object can request its services, but , of an object can request its services, but it should not have to be aware of how those services are it should not have to be aware of how those services are accomplishedaccomplished
14
EncapsulationEncapsulation An encapsulated object can be thought of as a An encapsulated object can be thought of as a black boxblack box Its inner workings are hidden to the client, which only Its inner workings are hidden to the client, which only
invokes the interface methodsinvokes the interface methods
ClientClient Methods
Data
15
Visibility ModifiersVisibility Modifiers Members of a class that are declared with Members of a class that are declared with public visibilitypublic visibility
can be accessed from anywherecan be accessed from anywhere
Members of a class that are declared with Members of a class that are declared with private visibilityprivate visibility can only be accessed from inside the classcan only be accessed from inside the class
Members declared without a visibility modifier have Members declared without a visibility modifier have default default visibilityvisibility and can be accessed by any class in the same and can be accessed by any class in the same packagepackage
Java modifiers are discussed in detail in Appendix FJava modifiers are discussed in detail in Appendix F
16
Visibility Modifiers: Rules of Visibility Modifiers: Rules of thumbthumb Instance data should be Instance data should be privateprivate
service methodsservice methods should be should be publicpublic
support methods support methods should be should be privateprivate
Method Declarations RevisitedMethod Declarations Revisited A method declaration begins with a A method declaration begins with a method headermethod header
public char calc (int num1, int num2, String message)
methodmethodnamename
returnreturntypetype
parameter listparameter list
The parameter list specifies the typeThe parameter list specifies the typeand name of each parameterand name of each parameter
The name of a parameter in the methodThe name of a parameter in the methoddeclaration is called a declaration is called a formal argumentformal argument
visibilityvisibilitymodifiermodifier
Method DeclarationsMethod Declarations The method header is followed by the The method header is followed by the method bodymethod body
char calc (int num1, int num2, String message){ int sum = num1 + num2; char result = message.charAt (sum);
return result;}
• Must be consistent with return typeMust be consistent with return type• A method that does not return a value A method that does not return a value has ahas a void void return typereturn type
sumsum and and resultresultare are local datalocal data
They are created each They are created each time the method is called, time the method is called, and are destroyed when and are destroyed when it finishes executingit finishes executing
ParametersParameters Each time a method is called, the Each time a method is called, the actual argumentsactual arguments in the invocation are copied in the invocation are copied
into the formal argumentsinto the formal arguments
char calc (int num1, int num2, String message){ int sum = num1 + num2; char result = message.charAt (sum);
return result;}
ch = obj.calc (25, count, "Hello");
20
Constructors Constructors Constructor: special method to create and set up a new objectConstructor: special method to create and set up a new object
• it has the same name as the classit has the same name as the class• it does not return a valueit does not return a value• it has no return type, not evenit has no return type, not even void void• it often sets the initial values of instance variables it often sets the initial values of instance variables • default constructor gets created if you do not define onedefault constructor gets created if you do not define one
Writing ClassesWriting Classes Sometimes an object has to interact with other objects of Sometimes an object has to interact with other objects of
the same typethe same type For example, we might add two For example, we might add two RationalRational number objects number objects
together as follows:together as follows:
r3 = r1.add(r2);
One object (One object (r1r1) is executing the method and another () is executing the method and another (r2r2) ) is passed as a parameteris passed as a parameter
See RationalNumbers.javaSee RationalNumbers.java (page 196)(page 196) See Rational.java (page 197)See Rational.java (page 197)
22
Overloading MethodsOverloading Methods Method overloadingMethod overloading is the process of using the same method is the process of using the same method
name for multiple methodsname for multiple methods
The The signaturesignature of each overloaded method must be unique of each overloaded method must be unique
The signature includes the number, type, and order of the The signature includes the number, type, and order of the parametersparameters
The return type of the method is The return type of the method is notnot part of the signature part of the signature
Overloading MethodsOverloading Methods
float tryMe (int x){ return x + .375;}
Version 1Version 1
float tryMe (int x, float y){ return x*y;}
Version 2Version 2
result = tryMe (25, 4.32)
InvocationInvocation
24
Overloaded MethodsOverloaded Methods TheThe println println method is overloaded:method is overloaded:
println (String s)println (String s) println (int i)println (int i) println (double d)println (double d)
etc.etc.
The following lines invoke different versions of theThe following lines invoke different versions of the println println method:method:
System.out.println ("The total is:");System.out.println ("The total is:"); System.out.println (total);System.out.println (total);
25
Overloading MethodsOverloading Methods Constructors can be overloadedConstructors can be overloaded An overloaded constructor provides multiple ways to set up An overloaded constructor provides multiple ways to set up
a new objecta new object
See SnakeEyes.javaSee SnakeEyes.java (page 203)(page 203) See Die.javaSee Die.java (page 204)(page 204)
The StringTokenizer ClassThe StringTokenizer Class The The StringTokenizerStringTokenizer class is defined in class is defined in java.utiljava.util
A A StringTokenizerStringTokenizer object separates a string into smaller object separates a string into smaller substrings (tokens)substrings (tokens)
nextTokennextToken method returns the next token in the string method returns the next token in the string
Two constructors:Two constructors: StringTokenizer (String str, String delimitersStringTokenizer (String str, String delimiters) ) StringTokenizer (String str)StringTokenizer (String str)
• By default, string is separated at white spaceBy default, string is separated at white space
27
Program DevelopmentProgram Development The creation of software involves four basic activities:The creation of software involves four basic activities:
• establishing the requirementsestablishing the requirements• creating a designcreating a design• implementing the codeimplementing the code• testing the implementationtesting the implementation
The development process is much more involved than this, The development process is much more involved than this, but these basic steps are a good starting pointbut these basic steps are a good starting point
28
RequirementsRequirements RequirementsRequirements specify the tasks a program must accomplish specify the tasks a program must accomplish
(what to do, not how to do it)(what to do, not how to do it) They often include a description of the user interfaceThey often include a description of the user interface An initial set of requirements are often provided, but An initial set of requirements are often provided, but
usually must be critiqued, modified, and expandedusually must be critiqued, modified, and expanded It is often difficult to establish detailed, unambiguous, It is often difficult to establish detailed, unambiguous,
complete requirementscomplete requirements Careful attention to the requirements can save significant Careful attention to the requirements can save significant
time and money in the overall projecttime and money in the overall project
29
DesignDesign An An algorithmalgorithm is a step-by-step process for solving a problem is a step-by-step process for solving a problem A program follows one or more algorithms to accomplish A program follows one or more algorithms to accomplish
its goalits goal The The designdesign of a program specifies the algorithms and data of a program specifies the algorithms and data
neededneeded In object-oriented development, the design establishes the In object-oriented development, the design establishes the
classes, objects, and methods that are requiredclasses, objects, and methods that are required The details of a method may be expressed in The details of a method may be expressed in pseudocodepseudocode, ,
which is code-like, but does not necessarily follow any which is code-like, but does not necessarily follow any specific syntaxspecific syntax
Method DecompositionMethod Decomposition A method should be relatively small, so that it can be A method should be relatively small, so that it can be
readily understood as a single entityreadily understood as a single entity
A potentially large method should be decomposed into A potentially large method should be decomposed into several smaller methods as needed for clarityseveral smaller methods as needed for clarity
Therefore, a service method of an object may call one or Therefore, a service method of an object may call one or more support methods to accomplish its goalmore support methods to accomplish its goal
See PigLatin.javaSee PigLatin.java (page 207)(page 207) See See PPigLatinTranslatoigLatinTranslator.java r.java (page 208)(page 208)
31
ImplementationImplementation ImplementationImplementation is the process of translating a design into is the process of translating a design into
source codesource code Most novice programmers think that writing code is the Most novice programmers think that writing code is the
heart of software development, but it actually should be the heart of software development, but it actually should be the least creative stepleast creative step
Almost all important decisions are made during Almost all important decisions are made during requirements analysis and designrequirements analysis and design
Implementation should focus on coding details, including Implementation should focus on coding details, including style guidelines and documentationstyle guidelines and documentation
32
TestingTesting A program should be executed multiple times with various A program should be executed multiple times with various
input sets in an attempt to find errorsinput sets in an attempt to find errors DebuggingDebugging is the process of discovering the cause of a is the process of discovering the cause of a
problem and fixing itproblem and fixing it Programmers often erroneously think that there is "only Programmers often erroneously think that there is "only
one more bug" to fixone more bug" to fix Tests should focus on design details as well as overall Tests should focus on design details as well as overall
requirementsrequirements