Download presentation
Presentation is loading. Please wait.
Published byErnest Carter Modified over 8 years ago
1
Lecture 4 b Writing Classes b class declarations b method declarations b constructors b instance variables b encapsulation b method overloading b program development
2
2 Objects b An object has: state - descriptive characteristicsstate - descriptive characteristics behaviors - what it can do (or be done to it)behaviors - what it can do (or be done to it) Example: String state - characters comprising the stringstate - characters comprising the string behaviors - services, such as toUpperCasebehaviors - services, such as toUpperCase b Example: coin state - "heads" or "tails”state - "heads" or "tails” behaviors - “flip” (may change its state)behaviors - “flip” (may change its state) b A class is a blueprint of an object
3
Classes: Create your own b A class contains data declarations and method declarations int x, y; char ch; Data declarations Method declarations
4
Classes: Brew your own b The scope of data is the area in a program in which that data can be used (referenced) int x, y; char ch; Data declared at class level can be used by all methods in class Local data: - can only be used in these methods int x, y, z; char ch; int x, w; int z, y; char ch;
5
Writing Methods b A method declaration specifies the code that will be executed when the method is invoked (or called) b When a method is invoked, the flow of control jumps to the method and executes its code b When complete, the flow returns to the place where the method was called and continues b The invocation may or may not return a value, depending on how the method was defined
6
myMethod(); myMethodcompute Method Control Flow b The called method could be within the same class, in which case only the method name is needed
7
doIt helpMe helpMe(); obj.doIt(); main Method Control Flow b The called method could be part of another class or object
8
The Coin Class In our Coin class we could define the following data: face, an integer that represents the current faceface, an integer that represents the current face HEADS and TAILS, integer constants that represent the two possible statesHEADS and TAILS, integer constants that represent the two possible states b We might also define the following methods: a Coin constructor, to set up the objecta Coin constructor, to set up the object a flip method, to flip the coina flip method, to flip the coin a getFace method, to return the current facea getFace method, to return the current face a toString method, to return a string for printinga toString method, to return a string for printing
9
The Coin Class b See CountFlips.java (page 179) CountFlips.java b See Coin.java (page 180) Coin.java Once the Coin class has been defined, we can use it again in other programs as needed Note that the CountFlips program did not use the toString method b A program will not necessarily use every service provided by an object
10
Instance Data The face variable in the Coin class is called instance data because each instance (object) of the Coin class has its own b A class declares the type of the data, but it does not reserve any memory space for it Every time a Coin object is created, a new face variable is created as well b The objects of a class share the method definitions, but they have unique data space b That's the only way two objects can have different states
11
Instance Data b See FlipRace.java (page 182) FlipRace.java face 0 coin1 int face; class Coin face 1 coin2
12
12 Encapsulation b 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 programexternal - the interaction of the object with other objects in the program b From the external view, an object is an encapsulated entity, providing a set of specific services b Services define the interface to the object b Objects are thus abstractions hiding details from the rest of the systemhiding details from the rest of the system
13
13 Encapsulation b An object should be self-governing b Any changes to the object's state (its variables) should be accomplished by that object's methods b We should make it difficult, if not impossible, for one object to "reach in" and alter another object's state b The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished
14
14 Encapsulation b An encapsulated object can be thought of as a black box b Its inner workings are hidden to the client, which only invokes the interface methods Client Methods Data
15
15 Visibility Modifiers b Members of a class that are declared with public visibility can be accessed from anywhere b Members of a class that are declared with private visibility can only be accessed from inside the class b Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package b Java modifiers are discussed in detail in Appendix F
16
16 Visibility Modifiers: Rules of thumb Instance data should be private service methods should be public support methods should be private
17
Method Declarations Revisited b A method declaration begins with a method header public char calc (int num1, int num2, String message) methodname returntype parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument visibilitymodifier
18
Method Declarations b The method header is followed by the method 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 type Must be consistent with return type A method that does not return a value has a void return type A method that does not return a value has a void return type sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing
19
Parameters b Each time a method is called, the actual arguments in the invocation are copied into 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
20 Constructors b Constructor: 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 even voidit has no return type, not even void it often sets the initial values of instance variablesit 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
21
Writing Classes b Sometimes an object has to interact with other objects of the same type For example, we might add two Rational number objects together as follows: r3 = r1.add(r2); One object ( r1 ) is executing the method and another ( r2 ) is passed as a parameter b See RationalNumbers.java (page 196) RationalNumbers.java b See Rational.java (page 197) Rational.java
22
22 Overloading Methods b Method overloading is the process of using the same method name for multiple methods b The signature of each overloaded method must be unique b The signature includes the number, type, and order of the parameters b The return type of the method is not part of the signature
23
Overloading Methods float tryMe (int x) { return x +.375; } Version 1 float tryMe (int x, float y) { return x*y; } Version 2 result = tryMe (25, 4.32)Invocation
24
24 Overloaded Methods The println 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 the println method: System.out.println ("The total is:"); System.out.println ("The total is:"); System.out.println (total); System.out.println (total);
25
25 Overloading Methods b Constructors can be overloaded b An overloaded constructor provides multiple ways to set up a new object b See SnakeEyes.java (page 203) SnakeEyes.java b See Die.java (page 204) Die.java
26
The StringTokenizer Class The StringTokenizer class is defined in java.util A StringTokenizer object separates a string into smaller substrings (tokens) nextToken method returns the next token in the string Two constructors: StringTokenizer (String str, String delimiters ) StringTokenizer (String str) By default, string is separated at white spaceBy default, string is separated at white space
27
27 Program Development b 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 b The development process is much more involved than this, but these basic steps are a good starting point
28
28 Requirements b Requirements specify the tasks a program must accomplish (what to do, not how to do it) b They often include a description of the user interface b An initial set of requirements are often provided, but usually must be critiqued, modified, and expanded b It is often difficult to establish detailed, unambiguous, complete requirements b Careful attention to the requirements can save significant time and money in the overall project
29
29 Design b An algorithm is a step-by-step process for solving a problem b A program follows one or more algorithms to accomplish its goal b The design of a program specifies the algorithms and data needed b In object-oriented development, the design establishes the classes, objects, and methods that are required b The details of a method may be expressed in pseudocode, which is code-like, but does not necessarily follow any specific syntax
30
Method Decomposition b A method should be relatively small, so that it can be readily understood as a single entity b A potentially large method should be decomposed into several smaller methods as needed for clarity b Therefore, a service method of an object may call one or more support methods to accomplish its goal b See PigLatin.java (page 207) PigLatin.java b See PigLatinTranslator.java (page 208) PigLatinTranslator.java PigLatinTranslator.java
31
31 Implementation b Implementation is the process of translating a design into source code b Most novice programmers think that writing code is the heart of software development, but it actually should be the least creative step b Almost all important decisions are made during requirements analysis and design b Implementation should focus on coding details, including style guidelines and documentation
32
32 Testing b A program should be executed multiple times with various input sets in an attempt to find errors b Debugging is the process of discovering the cause of a problem and fixing it b Programmers often erroneously think that there is "only one more bug" to fix b Tests should focus on design details as well as overall requirements
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.