Class Example - Rationals Rational numbers are represented by the ratio of two integers, a numerator and a denominator, e.g., 2/3. This is opposed to irrational.

Slides:



Advertisements
Similar presentations
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Advertisements

Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Road Map Introduction to object oriented programming. Classes
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Chapter 6: User-Defined Functions I
Introduction to C Programming
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CSE 131 Computer Science 1 Module 1: (basics of Java)
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
Case Study - Fractions Timothy Budd Oregon State University.
CHAPTER 4: CONTROL STRUCTURES - SEQUENCING 10/14/2014 PROBLEM SOLVING & ALGORITHM (DCT 1123)
CPS120: Introduction to Computer Science Decision Making in Programs.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Procedural programming in Java Methods, parameters and return values.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
SE-1010 Dr. Mark L. Hornick 1 Java Programming Basics.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
Arithmetic Expressions Addition (+) Subtraction (-) Multiplication (*) Division (/) –Integer –Real Number Mod Operator (%) Same as regular Depends on the.
Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Class Example - Rationals Rational numbers are represented by the ratio of two integers, a numerator and a denominator, e.g., 2/3. This is opposed to irrational.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
Invoking methods in the Java library. Jargon: method invocation Terminology: Invoking a method = executing a method Other phrases with exactly the same.
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
A Sample Program #include using namespace std; int main(void) { cout
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
User-Written Functions
Chapter 6: User-Defined Functions I
Java Primer 1: Types, Classes and Operators
2.5 Another Java Application: Adding Integers
Multiple variables can be created in one declaration
Variables and Arithmetic Operators in JavaScript
Chapter 3: Using Methods, Classes, and Objects
Lecture Set 4 Data Types and Variables
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Classes, Objects, and Methods
Introduction to C++ Programming
Chapter 6: User-Defined Functions I
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Classes, Objects and Methods
Names of variables, functions, classes
Class Example - Rationals
Corresponds with Chapter 5
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Class Example - Rationals Rational numbers are represented by the ratio of two integers, a numerator and a denominator, e.g., 2/3. This is opposed to irrational numbers which cannot be expressed as the ratio of two integers, such as Pi. Rational numbers are usually put into lowest terms, which is done by dividing the numerator and denominator by the greatest common denominator (GCD) of both: 4/6 -> 2/3.

Rationals (cont'd) Rational numbers are not a built-in type like int s and double s. Suppose that we what to work with them as a new type. We can create a new Rational class that represents rational numbers and incorporates the usual operators that we apply to numbers: add, subtract, multiply, and divide. In addition, we want to be able to read and write rational numbers in human-readable form.

Rational Methods The arithmetic operators all take two operands (both rational) and return a third value (also a rational). When we implement this, one of the operands will be the object that the method is called upon and the second operand will be explicitly passed as an input parameter to the method. The return value will be used to return the result. For example, to add two rational numbers together we say: c = a.add(b);

Rational Operators n 1 /d 1 + n 2 /d 2 = (n 1 * d 2 + n 2 * d 1 ) / (d 1 * d 2 ) n 1 /d 1 - n 2 /d 2 = (n 1 * d 2 - n 2 * d 1 ) / (d 1 * d 2 ) n 1 /d 1 * n 2 /d 2 = (n 1 * n 2 ) / (d 1 * d 2 ) n 1 /d 1 / n 2 /d 2 = (n 1 * d 2 ) / (n 2 * d 1 )

Representing Rational Numbers To represent a rational number, we will need to store the numerator and the denominator, both int s. private int n, d; We use the private modifier so that the parts cannot be accessed from outside the Rational class (information hiding).

A Rational Method public Rational add(Rational b) { Rational c = new Rational(); c.n = n * b.d + b.n * d; c.d = d * b.d; return c; } The variables n and d (which are not qualified) refer to the values of the object upon which the add methods is called. In the example c = a.add(b); the add method is called on object a, so n and d refer to a 's fields.

Other Methods public Rational subtract(Rational b) { Rational c = new Rational(); c.n = n * b.d - b.n * d; c.d = d * b.d; return c; } public Rational multiply(Rational b) { Rational c = new Rational(); c.n = n * b.n; c.d = d * b.d; return c; }

Other Methods (cont'd) public Rational divide(Rational b) { Rational c = new Rational(); c.n = n * b.d; c.d = b.n * d; return c; }

Rational Class public class Rational { private int n,d; public Rational add(Rational b) {... } public Rational subtract(Rational b) {...} public Rational multiply(Rational b) {... } public Rational divide(Rational b) {... } }

Additional Methods For the time being we will also write two additional methods so we can test our class: public void set(int n0, int d0) { n = n0; d = d0; } public String toString() { return n + " / " + d; }

Testing the Rational Class The following main program will test the methods of the Rational class: public class Main2 { public static void main(String args[]) { Rational a = new Rational(); Rational b = new Rational(); a.set(1,3); b.set(2,3); Rational c = a.add(b); System.out.println(c); } The result of this program is: 9/9

Oops! What have we forgotten? The rational number should be represented in lowest terms, so 9/9 isn't quite right. The GCD of the numerator and the denominator is 9, so dividing both by the GCD 9, yields 1/1, which is the rational number in lowest terms.

Calculating the GCD Finding the GCD is one of the oldest known algorithms, ascribed to Euclid (hence Euclid's algorithm). We find the GCD by repeatedly taking the remainder of one number divided by the other until one of the terms becomes 0. The other term is the gcd. This works because the gcd(x,y) = gcd(x, x % y).

Euclid's Algorithm private int gcd(int a, int b) { while (b != 0) { int t = b; b = a % b; a = t; } return a; }

Reduce method To avoid writing the same code over and over again, we also write a reduce method, that takes a Rational number, reduces it to lowest form, and returns it: private Rational reduce() { int g = gcd(n,d); n /= g; d /= g; return this; }

Reduce method (cont'd) Two things to note:  Both reduce and gcd are private methods. That is, they can only be called by other methods of the Rational class, and not from any other class.  reduce returns this, which refers to the (anonymous) object upon which reduce was called.

New add method public Rational add(Rational b) { Rational c = new Rational(); c.n = n * b.d + b.n * d; c.d = d * b.d; return c.reduce(); }

Methods  A program takes input, does some calculation, and produces output.  A method is a miniature program – it also is given input, does some calculation, and produces some output.  Most methods are called, or invoked, by other methods.  The main method is invoked when the program is run.

Method Declarations  Every method is part of a class.  Classes include method declarations.  The declaration tells us who can call the method, what kind of value the method returns (if any), the name of the method, the method's parameters, and its code.  The parameters are how we pass information into the method.

Example public Rational add(Rational b) { Rational c = new Rational(); c.n = n * b.d + b.n * d; c.d = d * b.d; return c.reduce(); } This method is public, i.e., anyone can call it. It returns a Rational number, it's name is “add”, and it takes one argument, also a Rational number.

Syntax of a Method Declaration ( ) { } where is one of public, private, protected, or is elided. is a type, but may be void. is the name of the method. is a comma-separated list of parameters. is the code of the method.

Functions and Procedures  A method may or may not return a value.  Methods that do return values are often called functions.  Methods that do not return values are often called procedures.  A procedure always has the return type void, which is a special type that has no values.  A procedure should not try to return a value in its code.

Invoking a Method  The syntax for invoking an object method is:. ( )  Object methods are called on objects.  is the name of the method to be called.  are the values that are passed into the method, i.e., the values that the corresponding parameters are initialized to.

Invoking a Function  A function is usually invoked by using it in an expression.  A function can appear anywhere that a variable or a literal of its return type can appear in an expression, e.g., a boolean function can occur anywhere a boolean variable or literal could occur.  The function is evaluated, and the return value is used in place of the function call in the expression.

Invoking a Function, cnt'd  A function may not be used on the left-hand side of an assignment statement, e.g., a.add(b) = c; is not legal.  A function may be used on the right-hand side of an assignment statement, e.g., c = a.add(b);

Invoking a Procedure  Procedures are usually invoked by making them statements, i.e., adding a semicolon after the call.  Procedure invocations may not appear as part of an expression.  If the return value of a method is void, do not use it in an expression.  A function may be called as a statement, by adding a semicolon after. Its value is simply ignored.

Parameters  Methods may have parameters.  Parameters are used to pass information into the method.  Each parameter is specified by giving it a type and an identifier, just like variables.  The parameter list is a comma-separated list of parameters.  A method may have no parameters, but it still needs parentheses.

Method invocation  When a method is called, the arguments are evaluated and their values are used to initialize the parameters.  The arguments and parameters must match in number and type. If possible, type conversion will be done on the values.  Control is transferred to the body of the method.  The methods returns a value (if any) to the calling method, using the return statement.

Method code  The code of a method is a miniature program.  It may contain local variables.  When the method is called, the parameters are initialized to the values of the arguments, and the code of the method is executed.  A return statement will cause the method to be terminated. If it is of the form return then value must be of the right type and is returned as the value of the method.

Arguments and Parameters  (Actual) arguments are part of the method invocation.  Arguments are expressions. They may be variables, literals, or use operators.  The argument list does not contain types.  (Formal) Parameters are part of the method declaration.  The parameter list does contain types.

Message and Methods  Different classes may have methods with the same name and number and types of arguments (the method signature).  A message of the same name (and arguments) may be called upon (or sent to) objects of different types, e.g., snowman.moveForward, iceSkater.moveForward()  The method invoked depends on both the type of the object and the message sent.