Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming: Guided Learning with Early Objects

Similar presentations


Presentation on theme: "Java Programming: Guided Learning with Early Objects"— Presentation transcript:

1 Java Programming: Guided Learning with Early Objects
Chapter 6 User-Defined Methods and Classes

2 Objectives Learn how methods are used in Java programming
Understand actual and formal parameters Explore how to construct and use user-defined methods in a program Explore variables as parameters Learn about the scope of an identifier Java Programming: Guided Learning with Early Objects

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 The class StringBuffer
Strings assigned to StringBuffer variables can be altered Method append appends to an existing string Method delete deletes all characters in a string Assignment operator cannot be used with StringBuffer Must use new operator Java Programming: Guided Learning with Early Objects

12 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

13 Parameters and Memory Allocation
Local variables: memory for 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 Figure 6-15 UML class diagram of the class Clock
Java Programming: Guided Learning with Early Objects

23 Definitions of the Constructors and Methods of the class Clock
Method setTime 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 myClock.setTime(3, 48, 52); Java Programming: Guided Learning with Early Objects

24 Figure 6-16 Object myClock
Figure myClock after statement myClock.setTime(3,48,52); executes Java Programming: Guided Learning with Early Objects

25 Definitions of the Constructors and Methods of the class Clock (continued)
Method equals: public boolean equals(Clock otherClock) { return (hr == otherClock.hr && min == otherClock.min && sec == otherClock.sec); } if (myClock.equals(yourClock)) Within method of class, object of class can access private data members Java Programming: Guided Learning with Early Objects

26 Figure 6-18 Objects myClock and yourClock
Java Programming: Guided Learning with Early Objects

27 Figure 6-19 Object myClock and parameter otherClock
Java Programming: Guided Learning with Early Objects

28 Definitions of the Constructors and Methods of the class Clock (continued)
Method getCopy: public Clock getCopy() { Clock temp = new Clock(hr, min, sec); return temp; } myClock = yourClock.getCopy(); Object pointed to by temp is a copy of object pointed to by yourClock Java Programming: Guided Learning with Early Objects

29 Figure 6-21 Objects temp and yourClock
Java Programming: Guided Learning with Early Objects

30 Figure 6-22 Objects myClock and yourClock
Java Programming: Guided Learning with Early Objects

31 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

32 Variable Declaration and Object Instantiation
Once a class is defined, you can declare reference variables of that class type: Clock myClock = new Clock(); yourClock = new Clock(9, 35, 15); You can combine declaration and instantiation: Clock myClock = new Clock(9, 35, 15); An object is an instance of a class Java Programming: Guided Learning with Early Objects

33 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: refVarName.methodName(actual params); Java Programming: Guided Learning with Early Objects

34 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

35 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

36 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

37 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

38 Copy Constructor Copy constructor: executes when object instantiated
Initialized using existing object Syntax: public ClassName(ClassName otherObject) Example: public Clock (Clock otherClock) { hr = otherClock.hr; min = otherClock.min; sec = otherClock.sec; } Java Programming: Guided Learning with Early Objects

39 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

40 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

41 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

42 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

43 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

44 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

45 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 StringBuffer useful to alter strings Java Programming: Guided Learning with Early Objects

46 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

47 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

48 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

49 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

50 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


Download ppt "Java Programming: Guided Learning with Early Objects"

Similar presentations


Ads by Google