Java Programming: Guided Learning with Early Objects

Slides:



Advertisements
Similar presentations
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Advertisements

C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 14: Overloading and Templates
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
Chapter 8 User-Defined Classes and ADTs. Chapter Objectives Learn about classes Learn about private, protected, public, and static members of a class.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Chapter 8: User-Defined Classes and ADTs J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 7 User-Defined Methods.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CHAPTER 13 CLASSES AND DATA ABSTRACTION. In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class.
Data Structures Using C++1 Chapter 1 -Software Engineering Principles -ADT and Classes.
Chapter 8: User-Defined Classes and ADTs
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Chapter 8: User-Defined Classes and ADTs J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
Data Structures Using Java1 Chapter 1 Software Engineering Principles and Java Classes.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Defining Classes and Methods
More About Objects and Methods
Java Programming: Guided Learning with Early Objects
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Object-Oriented Programming: Classes and Objects
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
Object-Oriented Programming: Classes and Objects
User-Defined Functions
User-Defined Classes and ADTs
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Defining Classes and Methods
Chapter 6 Methods: A Deeper Look
CHAPTER 6 GENERAL-PURPOSE METHODS
Chapter 8: User-Defined Classes and ADTs
Classes and Objects.
User-Defined Classes and ADTs
Defining Classes and Methods
Chapter 8 Classes User-Defined Classes and ADTs
Chapter 7: User-Defined Functions II
Object Oriented Programming in java
Defining Classes and Methods
Defining Classes and Methods
Corresponds with Chapter 5
Presentation transcript:

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 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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