Java Programming Guided Learning with Early Objects Chapter
Java Programming: Guided Learning with Early Objects Chapter 6 User-Defined Methods and Classes
Objectives • Learn how methods are used in Java programming • Understand actual and formal parameters • Explore how to construct and user-defined methods in a program • Explore variables as parameters • Learn about the scope of an identifier Java Programming: Guided Learning with Early Objects 2
Objectives (continued) • • Become acquainted with method overloading Learn more about operations on classes Learn about the copy constructor Become acquainted with accessor methods and mutator methods • Learn about the reference this Java Programming: Guided Learning with Early Objects 3
User-Defined Methods • Methods are the building blocks of a program – Divide programs into manageable pieces • Advantages of using methods: – Focus on one part of the program, construct it, debug it, perfect it – Different people work on program at same time – Method can be reused – Methods reduce complexity • Methods often called modules Java Programming: Guided Learning with Early Objects 4
Primitive Data Type Variables as Parameters • When method is called, actual parameter copied to formal parameter – Formal parameter a separate copy of actual parameter • Formal parameter manipulates only data stored in its own memory space – Has no functional connection with actual parameter • Actual parameter not affected by the formal parameter Java Programming: Guided Learning with Early Objects 5
Reference Variables as Parameters • Actual parameter copied to formal parameter • Reference variable contains memory address • After copying, both formal parameter and actual parameter point to same memory location • Formal parameter changes the value in the memory location; actual parameter changes Java Programming: Guided Learning with Early Objects 6
Reference Variables as Parameters (continued) • Reference variables provide access via methods to values associated with objects • Useful in three situations: – When returning more than one value – When value of object needs to be changed – When passing the address would save memory space and time relative to copying data Java Programming: Guided Learning with Early Objects 7
Reference Variables of the String Type as Parameters: A Precaution • Recall String variables can be instantiated using assignment operator or new String str = “Hello”; Figure 6 -5 Variable str and the String object Java Programming: Guided Learning with Early Objects 8
Reference Variables of the String Type as Parameters: A Precaution (continued) • If we change the value of the string, a new location is allocated str = str + “ There”; str = “Hello There”; Figure 6 -6 str after the statement str = “Hello There”; or statement str = str + “ There”; executes Java Programming: Guided Learning with Early Objects 9
Reference Variables of the String Type as Parameters: A Precaution (continued) • When different string assigned to a String variable, it points to different object • A String object cannot be changed • When passing String to a method: – If altering a string with the assignment operator: • String of actual parameter remains unchanged • New string assigned to formal parameter Java Programming: Guided Learning with Early Objects 10
The class String. Buffer • Strings assigned to String. Buffer variables can be altered • Method appends to an existing string • Method deletes all characters in a string • Assignment operator cannot be used with String. Buffer – Must use new operator Java Programming: Guided Learning with Early Objects 11
Primitive Type Wrapper Classes as Parameters • Changing value of formal parameter of primitive type has no effect on actual parameter • Only reference variables pass values outside the method • Primitives can be wrapped in wrapper classes • Objects of wrapper classes have same limitations as objects of class String Java Programming: Guided Learning with Early Objects 12
Parameters and Memory Allocation • Local variables: memory formal parameters, variables declared in method body – Allocated in method data area • Value of each actual parameter copied into memory cell of corresponding formal parameter • If parameter is an object, actual and formal parameter point to same memory location Java Programming: Guided Learning with Early Objects 13
Scope of an Identifier within a Class • Scope: parts of the program that can access an identifier • Local identifier: declared within a method or block, visible only within that method or block • Java does not allow nesting methods • Within method or block, identifier must be declared before it can be used • Within a class, outside any method or block, identifier can be declared anywhere Java Programming: Guided Learning with Early Objects 14
Scope of an Identifier within a Class (continued) • Identifiers in outer block of method cannot be used for variable in inner block • Identifier declared in method accessible: – Within the block from the point of declaration until end of block – By blocks that are nested within that block • Identifier declared within class, outside method: – Non static identifiers cannot be accessed within static method – static identifier accessed within method block Java Programming: Guided Learning with Early Objects 15
Method Overloading: An Introduction • Method overloading: several methods have the same name in the class • Different formal parameter lists: – Different number of formal parameters – Data type differs in at least one position • Method signature: method name and formal parameter list • Method overloading used when same action for different types of data Java Programming: Guided Learning with Early Objects 16
Avoiding Bugs: One-Piece-at-a-Time Design and Coding • Design decisions made during design phase: – Design of every class needed – How classes relate – Objects needed – Data elements and methods – Methods that provide services to user – Methods that provide support for other methods Java Programming: Guided Learning with Early Objects 17
Avoiding Bugs: One-Piece-at-a-Time Design and Coding (continued) • Divide-and-conquer: start with original problem, subdivide into smaller problems – Top-down design approach • Coding proceeds in similar manner – Method main corresponds to top level – Code small pieces at a time – First version is a working program with one feature • Add features one at a time Java Programming: Guided Learning with Early Objects 18
Avoiding Bugs: Using “Stubs” as Appropriate • • • Sometimes a method tested in isolation Sometimes testing in isolation not possible Method stub: method that is not fully coded Sufficient to permit it to be called Method stub permits work to progress on other parts of the solution Java Programming: Guided Learning with Early Objects 19
Classes and Objects • class Clock: – Three integers: hours, minutes, seconds – Sets, prints, copies the time – Returns hours, minutes, seconds, copy of time – Increments time by second, minute, hour – Compares two times – Two constructors, three instance variables • Instance methods: non static methods of a class Java Programming: Guided Learning with Early Objects 20
Unified Modeling Language Class Diagrams • Unified Modeling Language (UML): graphical notation for describing a class and its members • UML class diagram: – Top box: name of the class – Middle box: data members and data types – Bottom box: method names, parameter list, return types Java Programming: Guided Learning with Early Objects 21
Figure 6 -15 UML class diagram of the class Clock Java Programming: Guided Learning with Early Objects 22
Definitions of the Constructors and Methods of the class Clock • Method set. Time is void and has three parameters of type int – Call to this method is a stand-alone statement – Three parameters used in method call – Can access instance variables directly my. Clock. set. Time(3, 48, 52); Java Programming: Guided Learning with Early Objects 23
Figure 6 -16 Object my. Clock Figure 6 -17 my. Clock after statement my. Clock. set. Time(3, 48, 52); executes Java Programming: Guided Learning with Early Objects 24
Definitions of the Constructors and Methods of the class Clock (continued) • Method equals: public boolean equals(Clock other. Clock) { return (hr == other. Clock. hr && min == other. Clock. min && sec == other. Clock. sec); } if (my. Clock. equals(your. Clock)) • Within method of class, object of class can access private data members Java Programming: Guided Learning with Early Objects 25
Figure 6 -18 Objects my. Clock and your. Clock Java Programming: Guided Learning with Early Objects 26
Figure 6 -19 Object my. Clock and parameter other. Clock Java Programming: Guided Learning with Early Objects 27
Definitions of the Constructors and Methods of the class Clock (continued) • Method get. Copy: public Clock get. Copy() { Clock temp = new Clock(hr, min, sec); return temp; } my. Clock = your. Clock. get. Copy(); • Object pointed to by temp is a copy of object pointed to by your. Clock Java Programming: Guided Learning with Early Objects 28
Figure 6 -21 Objects temp and your. Clock Java Programming: Guided Learning with Early Objects 29
Figure 6 -22 Objects my. Clock and your. Clock Java Programming: Guided Learning with Early Objects 30
Definition of the class Clock public class Clock { private int hr; //store hours private int min; //store minutes private int sec; //store seconds //Place the definition of the //constructors and methods as //described previously here } Java Programming: Guided Learning with Early Objects 31
Variable Declaration and Object Instantiation • Once a class is defined, you can declare reference variables of that class type: Clock my. Clock = new Clock(); your. Clock = new Clock(9, 35, 15); • You can combine declaration and instantiation: Clock my. Clock = new Clock(9, 35, 15); • An object is an instance of a class Java Programming: Guided Learning with Early Objects 32
Accessing Class Members • Class members that the object can access depend on where the object is created • Object created in method definition of the class accesses public and private members • Object created elsewhere directly accesses only public members • Syntax: ref. Var. Name. method. Name(actual params); Java Programming: Guided Learning with Early Objects 33
Built-in Operations on Classes • Most built-in operations do not apply to classes • Arithmetic operations cannot be performed on classes • Relational operators cannot be used to compare classes • Dot operator applies to classes: – Reference variable accesses public members – Classes access public static members Java Programming: Guided Learning with Early Objects 34
Assignment Operator and Classes (Shallow Versus Deep Copying): A Precaution • Shallow copying: two or more reference variables point to the same object – Original object inaccessible • Deep copying: each reference variable points to its own object • Avoid shallow copying: object creates copy of itself, returns a reference Java Programming: Guided Learning with Early Objects 35
Class Scope • Reference variables follow same scope rules as other variables • Member of a class local to the class • Access public class member outside the class through reference variable and dot operator – Through the class name for static members Java Programming: Guided Learning with Early Objects 36
Methods and Classes • Reference variables passed as parameters to methods: – Returned as method values • Reference variable passed as parameter: – Formal and actual parameters point to same object • Program that uses objects of a class is called a client of the class Java Programming: Guided Learning with Early Objects 37
Copy Constructor • Copy constructor: executes when object instantiated – Initialized using existing object • Syntax: public Class. Name(Class. Name other. Object) • Example: public Clock (Clock other. Clock) { hr = other. Clock. hr; min = other. Clock. min; sec = other. Clock. sec; } Java Programming: Guided Learning with Early Objects 38
Static Members of a Class • Use the static import statement to access methods directly without class name – Available in Java 5. 0 • Otherwise, access method using class name and dot operator • Methods of class must be public static – static modifier specifies the member invoked using name of class Java Programming: Guided Learning with Early Objects 39
static Variables (Data Members) of a Class • When object instantiated, only non static data members become members of each object • Java allocates memory only once for static members – All reference variables to refer to same memory location • static data members of a class exist before any object of the class is instantiated • static variables initialized to default values Java Programming: Guided Learning with Early Objects 40
Accessor and Mutator Methods • Accessor methods: methods that access but do not modify data members • Mutator methods: methods that modify data members • Instance variables typically declared private – Client of class does not access them directly – Instance variables should never be public • Accessor and mutator methods provide access to private data members Java Programming: Guided Learning with Early Objects 41
Reference this (Optional) • Every object has access to a reference of itself – Reference named this • Compiler can distinguish between the instance variables and the formal parameters • If instance variable and formal parameter have same name: – Must use this to refer to instance variable Java Programming: Guided Learning with Early Objects 42
Inner Classes • Inner classes: classes that are defined within other classes • Complete class definition or an anonymous inner class definition • Anonymous classes have no name • Inner classes often used to handle events Java Programming: Guided Learning with Early Objects 43
Avoiding Bugs: Compiling/Testing Often • Unit: smallest testable piece of a program • Unit test: new piece works as intended by itself • Integration test: new piece works as intended together with previously coded pieces • Regression test: all previously coded features work properly after new feature added • Regression bugs discovered by redoing previous tests Java Programming: Guided Learning with Early Objects 44
Summary • Methods often called modules • Two types of methods: value-returning and void • Formal parameter: separate copy of actual parameter if primitive data type • Formal parameter: shallow copy of actual parameter if reference variable • class String. Buffer useful to alter strings Java Programming: Guided Learning with Early Objects 45
Summary (continued) • Wrapper classes for primitive types have same limitations as String class • Local variables are declared within a method • Local identifier declared and visible within a method or block • Methods with same name, different signature are said to be overloaded – Method signature: name and parameter list Java Programming: Guided Learning with Early Objects 46
Summary (continued) • Divide-and-conquer: subdivide problems into smaller problems • Method stubs allow work to progress on other parts of a solution • UML diagrams summarize data members and methods of a class • Shallow copying: two or more reference variables point to same object • Deep copying: reference variables point to separate objects Java Programming: Guided Learning with Early Objects 47
Summary (continued) • Member of a class is local to the class • Program that accesses objects of a class is a client of the class • Copy constructor executes when object is instantiated and initialized using existing object • Static modifier in a heading specifies the method can be invoked using name of the class • Static data members exist before any object of the class is instantiated Java Programming: Guided Learning with Early Objects 48
Summary (continued) • Static variables are initialized to their default values • Access public static data members outside the class • Accessor methods: access but do not modify data members • Mutator methods: modify data members • Every object has a reference to itself: this Java Programming: Guided Learning with Early Objects 49
Summary (continued) • Inner classes: classes defined within other classes • Anonymous classes: classes with no name • Inner classes often used for event handling • Unit testing verifies that new code works as intended on its own • Integration testing verifies that new code works as intended with previously coded pieces • Regression testing verifies that all previous coded features work after new feature added Java Programming: Guided Learning with Early Objects 50
- Slides: 50