Chapter 4 Defining Instantiable Classes

Slides:



Advertisements
Similar presentations
DONT PANIC!! Lots of new notions coming in these slides Dont worry if not all of it makes perfect sense Well meet most of this stuff again in detail later.
Advertisements

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.
Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Road Map Introduction to object oriented programming. Classes
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Chapter Four Defining Your Own Classes. Topics Instantiable classes Components of a class –constructors –accessors –mutators Visibility modifiers Class.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes Part 1.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four: Defining Your Own Classes *Instantiable.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four: Defining Your Own Classes *Instantiable.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 7 Defining Your Own Classes Part 2.
Chapter Four Defining Your Own Classes continued.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Why Programmer-Defined Classes Using just the String,
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Local Variables A local variable is a variable that is declared within a method declaration. Local variables are accessible only from the method in which.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Classes CS 21a: Introduction to Computing I First Semester,
Computer Programming 2 Lab(1) I.Fatimah Alzahrani.
CPS120: Introduction to Computer Science Functions.
Chapter 10 Introduction to Classes
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
Identifiers Identifiers in Java are composed of a series of letters and digits where the first character must be a letter. –Identifiers should help to.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Learners Support Publications Constructors and Destructors.
Chapter 7- Defining Your Own Classes Part 2 : Objectives After you have read and studied this chapter, you should be able to –Describe how objects are.
Constructors and Destructors
More About Objects and Methods
User-Written Functions
Review What is an object? What is a class?
Java Programming: Guided Learning with Early Objects
FUNCTIONS In C++.
Chapter 3: Using Methods, Classes, and Objects
by Tony Gaddis and Godfrey Muganda
Object-Oriented Programming & Design Lecture 14 Martin van Bommel
Chapter Topics Chapter 5 discusses the following main topics:
Pseudocode and Flowcharts
Chapter 3 Introduction to Classes, Objects Methods and Strings
Defining Your Own Classes Part 1
Defining Your Own Classes
Starting Out with Java: From Control Structures through Objects
CHAPTER 6 GENERAL-PURPOSE METHODS
IFS410 Advanced Analysis and Design
Introduction to Object-Oriented Programming with Java--Wu
Constructors and Destructors
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 6 – Methods Topics are:
Starting Out with Java: From Control Structures through Objects
Chapter 5 Processing Input with Applets
Classes CS 21a: Introduction to Computing I
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
DON’T PANIC!! Lots of new notions coming in these slides
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Chapter 4 Defining Instantiable Classes 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Introduction to Object-Oriented Programming with Java--Wu Chapter 4 Chapter 4 Objectives After you have read and studied this chapter, you should be able to Define an instantiable class with multiple methods and a constructor. Differentiate the local and instance variables. Define and use value-returning methods. Distinguish private and public methods. Distinguish private and public data members. Describe how the arguments are passed to the parameters in method definitions. Use System.out for temporary output to verify the program code. 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Building Large Programs Chapter 4 Building Large Programs Learning how to define instantiable classes is the first step toward mastering the skills necessary in building large programs. A class is instantiable if we can create instances of the class. The MainWindow, InputBox, and OutputBox classes are all instantiable classes while the Math class is not. In this chapter you will learn how to define instantiable classes and different types of methods included in the instantiable classes. The sample application programs we have written so far included only one class, the main class of the program. And the main class contained only one method, the main method. From this main method, we used only predefined classes from javabook and other standard packages such as java.lang. For small programs, this arrangement may be acceptable. But for large programs, it is not. We cannot develop large application programs in a similar manner for the following two reasons: Placing all programming code for a large application in a single method main makes the method very huge and impossible to manage. Predefined classes alone cannot satisfy all of our programming needs in writing a large application. 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Introduction to Object-Oriented Programming with Java--Wu CurrencyConverter Let’s start with an example to cover the basics of defining instantiable classes. In designing an instantiable class, we start with its specification, namely, how we want the class and its instances behave. A CurrencyConverter object will perform a conversion from a foreign currency and the U.S. dollar. What would be the most natural way for us to interact with CurrencyConverter objects? 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu

fromDollar and toDollar Methods We would like to have (at least) two methods for conversion: fromDollar and toDollar. CurrencyConverter yenConverter; yenConverter = new CurrencyConverter; double amountInYen = yenConverter.fromDollar( 500); double amountInUS = yenConverter.toDollar(15000); Converting $500 US to yen. Converting 15,000 yen to US dollar. 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu

setExchangeRate Methods Since the exchange rate fluctuates, we need a method to set the exchange rate. CurrencyConverter yenConverter; yenConverter = new CurrencyConverter; yenConverter.setExchangeRate( 106.55); $1.00 US = 106.55 yen 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu

Using Multiple Instances Once the CurrencyConverter class is defined, we can use its multiple instances. CurrencyConverter yenConverter, markConverter; double amountInYen, amountInMark, amountInDollar; yenConverter = new CurrencyConverter(); yenConverter.setExchangeRate(130.77); markConverter = new CurrencyConverter( ); markConverter.setExchangeRate(1.792); amountInYen = yenConverter.fromDollar( 200 ); amountInMark = markConverter.fromDollar( 200 ); amountInDollar = yenConverter.toDollar( 10000 ); amountInMark = markConverter.fromDollar(amountInDollar); 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu

Template for Class Definition Chapter 4 Template for Class Definition class { } . . . Import Statement Class Comment Describe the class in the javadoc format. Class Name Declarations Declare data members shared by multiple methods here. Methods For information on javadoc, please visit www.drcaffeine.com/additionaltopics. 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

The CurrencyConverter Class Chapter 4 The CurrencyConverter Class /** * This class is used to do the currency conversion * between a foreign currency and the U.S. dollar. * * @author Dr. Caffeine */ class CurrencyConverter { * how much $1.00 U.S. is worth in the foreign currency private double exchangeRate; //method declarations come here } Complete class definition is listed on pp151 – 152. 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Introduction to Object-Oriented Programming with Java--Wu Chapter 4 Method Declaration <modifier> <return type> <method name> ( <parameters> ) { <statements> } Statements Modifier Return Type Method Name Parameter public void setExchangeRagte ( double rate ) { exchangeRate = rate; } 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Value-Returning Method Chapter 4 Value-Returning Method We call a method that returns a value a value- returning method , or non-void method. A value-returning method must include a return statement in the following format: return <expression> ; public double toDollar( double foreignMoney ) { return (foreignMoney / exchangeRate); } 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Method Header Comment in javadoc Chapter 4 Method Header Comment in javadoc /** * Converts a given amount in dollars into * an equivalent amount in a foreign currency. * * @param dollar the amount in dollars to be converted * @return amount in foreign currency */ Each parameter is marked by the @param javadoc tag. Its syntax is @param <parameter name> <description> The <description> portion can go beyond one line. If the method returns a value, then we add the @return javadoc tag. Its syntax is @return <description> 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Introduction to Object-Oriented Programming with Java--Wu Documenting a class Let’s take a look at 151-152 You can model comments along these lines Don’t forget our header though 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu

Introduction to Object-Oriented Programming with Java--Wu Constructors A constructor is a special method that is executed when a new instance of the class is created. The purpose of the constructor is to initialize an object to a valid state. Whenever an object is created, we must ensure that it is created in a valid state by properly initializing all data members in a constructor. The name of a constructor must be the same as the name of the class. If no constructor is defined for a class (e.g., the original CurrencyConverter class), then the Java compiler will include a default constructor. 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu

Introduction to Object-Oriented Programming with Java--Wu Default Constructor The default constructor will have the following form: public <class name> ( ) { } A default constructor has no statements in its method body. public CurrencyConverter( ) { } 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu

Defining Constructors Chapter 4 Defining Constructors A constructor will have the following form: public <class name> ( <parameters ) { <statements> } Statements Modifier Class Name Parameter This constructor ensures that the value for exchangeRate is set when a new instance is created. Once we define our own constructor, such as public CurrencyConverter( double rate ) { exchangeRate = rate; } is defined, we will not be allowed to create a CurrencyConverter object as CurrencyConverter moneyChanger; moneyChanger = new CurrencyConverter( ); because no matching constructor is defined for the class. public CurrencyConverter( double rate ) { exchangeRate = rate; } 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Multiple Constructors Chapter 4 Multiple Constructors A class can include multiple constructors without any problem, as long as the constructors defined for the class have either A different number of parameters Different data types for the parameters if the number of parameters is the same public MyClass( int value ) { … } public MyClass( ) { … } public MyClass( float value ) { … } These constructors will not conflict with each other, and therefore, valid. It is possible to define multiple constructors for a class, so the programmer can create a new instance of the class in different ways. For example, if we want the programmers to create a new instance either as moneyChanger = new CurrencyConverter( ); or moneyChanger = new CurrencyConverter( 142.00 ); we simply define two constructors for the class. 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Visibility Modifiers: public and private Chapter 4 Visibility Modifiers: public and private The modifiers public and private designate the accessibility of data members and methods. If a class component (data member or method) is declared private, no outside methods can access it. If a class component is declared public, any outside method can access it. class Test { public int memberOne; private int memberTwo; } Test myTest = new MyTest(); myTest.memberOne = 10; myTest.memberTwo = 20; 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Data Members Should Be private Chapter 4 Data Members Should Be private Declare the data members (class and instance variables) private to ensure the integrity of the class. Data members are the implementation details of the class, and they should be kept invisible from the outside by declaring them private. If a data member is declared public, then we cannot make changes to the data member without affecting all the classes that made direct access to this data member. Constants can (should) be declared public if they are meant to be used directly by the outside methods. Although class constants should be declared public when direct access to them is desired, please note that once a constant is declared public, its name cannot be changed without affecting all the methods that made a direct access. So it is important to derive a good that you don’t have to change often, especially for the classes that are intended to be used by many programmers. 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Introduction to Object-Oriented Programming with Java--Wu Local Variables We covered instance and class variables that are shared among the methods of the class. A local variable is a variable that is declared within a method declaration. Local variables are accessible only from the method in which they are declared. Memory space for local variables are allocated only during the execution of the method. When the method execution completes, memory space will be deallocated. The parameters of a method are local to the method. 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu

Introduction to Object-Oriented Programming with Java--Wu Chapter 4 Sample Method Parameter Local Variables public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Memory Allocation for Local Variables - 1 Chapter 4 Memory Allocation for Local Variables - 1 Code A public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } amt = yenConverter.fromDollar( 200 ); At before fromDollar A A. Local variables do not exist before the method execution State of Memory 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Memory Allocation for Local Variables - 2 Chapter 4 Memory Allocation for Local Variables - 2 Code public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } amt = yenConverter.fromDollar( 200 ); B After is executed B dollar amount 200.0 fee B. Memory space is allocated for the local variables and parameter. State of Memory 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Memory Allocation for Local Variables - 3 Chapter 4 Memory Allocation for Local Variables - 3 Code public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } amt = yenConverter.fromDollar( 200 ); C After is executed C dollar amount 200.0 fee 24846.3 124.2315 C. Computed values are assigned to the local variables. State of Memory 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Memory Allocation for Local Variables - 4 Chapter 4 Memory Allocation for Local Variables - 4 Code public double fromDollar( double dollar ) { double amount, fee; fee = exchangeRate - feeRate; amount = dollar * fee; return amount; } amt = yenConverter.fromDollar( 200 ); D At after fromDollar D D. Memory space is deallocated upon exiting the fromDollar method. State of Memory 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Pass-By-Value Scheme - 1 Chapter 4 Pass-By-Value Scheme - 1 Code A x = 10; y = 20; tester.myMethod( x, y ); public void myMethod( int one, float two ) { one = 25; two = 35.4f; } At before myMethod A x 10 A. Local variables do not exist before the method execution y 10 20 State of Memory 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Pass-By-Value Scheme - 2 Chapter 4 Pass-By-Value Scheme - 2 Code x = 10; y = 20; tester.myMethod( x, y ); public void myMethod( int one, float two ) { one = 25; two = 35.4f; } B Values are copied at B x 10 one 10 B. The values of arguments are copied to the parameters. y 10 20 two 10 20.0f State of Memory 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Pass-By-Value Scheme - 3 Chapter 4 Pass-By-Value Scheme - 3 Code x = 10; y = 20; tester.myMethod( x, y ); public void myMethod( int one, float two ) { one = 25; two = 35.4f; } C After is executed C x 10 y 20 one 25 two 35.4f C. The values of parameters are changed. State of Memory 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Pass-By-Value Scheme - 4 Chapter 4 Pass-By-Value Scheme - 4 Code x = 10; y = 20; tester.myMethod( x, y ); public void myMethod( int one, float two ) { one = 25; two = 35.4f; } D At after myMethod D x 10 D. Parameters are erased. Arguments remain unchanged. y 10 20 State of Memory 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Arguments & Parameters: Points to Remember Chapter 4 Arguments & Parameters: Points to Remember Arguments are passed to a method using the pass-by-value scheme. Arguments are matched to the parameters from left to right. The data type of an argument must be assignment compatible to the data type of the matching parameter. The number of arguments in the method call must match the number of parameters in the method definition. Parameters and arguments do not have to have the same name. Local copies, which are distinct from arguments, are created even if the parameters and arguments share the same name. Parameters are input to a method, and they are local to the method. Changes made to the parameters will not affect the value of corresponding arguments. 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu

Sample Program: Using an Instantiable Class Problem Statement Write a loan calculator program that computes both monthly and total payments for a given loan amount, annual interest rate, and loan period. Major Tasks Get three input values Compute the monthly and total payments Output the results Key Formula L – loan amount R – monthly interest rate N – number of payments 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu

Introduction to Object-Oriented Programming with Java--Wu Program Design 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu

Introduction to Object-Oriented Programming with Java--Wu LoanCalculator Class Design 1 Design 2 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu

Loan Calculator – Development Steps Start with the main class and a skeleton of the LoanCalculator class. The skeleton LoanCalculator class will include only an object/variable declaration and a constructor to create objects. Implement the getInput method of LoanCalculator to accept three input values. Implement the displayOutput method of LoanCalculator to display the results. Implement the computePayment method of LoanCalculator to compute the monthly and total payments. Implement the describeProgram method of LoanCalculator to display a brief description of the program. 11/10/2018 Introduction to Object-Oriented Programming with Java--Wu