Object Oriented Design: Building a Fraction Class

Similar documents
Building a fraction class.

CIT 590 Homework 6 Fractions

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

CLASSES AND OBJECTS. Fundamentals of Computer Science I

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

Chapter 4 Defining Classes I

Programming via Java Defining classes

Object Oriented Programming COP3330 / CGS5409

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Chapter 7. Defining Your Own Classes Part 2. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 10 Writing Classes

CSE 373. Objects in Collections: Object; equals; compareto; mutability. slides created by Marty Stepp

Introduction to Classes and Objects. David Greenstein Monta Vista High School

What will this print?

Object Oriented Modeling

JAVA OPERATORS GENERAL

Rational number operations can often be simplified by converting mixed numbers to improper fractions Add EXAMPLE:

Classes and objects. Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates

Constructors.

More on Classes. The job of this method is to return a String representation of the object. Here is the tostring method from the Time class:

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Utilities (Part 2) Implementing static features

Classes and Objects in Java Instance Methods

COP 3330 Final Exam Review

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Section 2.3 Rational Numbers. A rational number is a number that may be written in the form a b. for any integer a and any nonzero integer b.

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Student Success Center Arithmetic Study Guide for the ACCUPLACER (CPT)

CS 101 Fall 2006 Midterm 3 Name: ID:

Prof. Navrati Saxena TA: Rochak Sachan

Recitation #2 Abstract Data Types, Collection Classes, and Linked List

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2013

A Fraction Class. Using a Fraction class, we can compute the above as: Assignment Objectives

Notes on Chapter Three

Algebra II Chapter 8 Part 2: Rational Functions

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

10/22/2018 Programming Data Structures

Name Student ID Number. Group Name. Group Members. Fractions

C212 Fall 2010 Final Exam Answers

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Introduction to Programming Using Java (98-388)

Initializers: Array initializers can be used with class base types as well. The elements of the initializer can be expressions (not just constants).

In our classes, we've had

Chapter 4. Defining Classes I

Lab 9: Creating a Reusable Class

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

CMP 326 Midterm Fall 2015

Carleton University Department of Systems and Computer Engineering SYSC Foundations of Imperative Programming - Winter Lab 8 - Structures

MODULE 02: BASIC COMPUTATION IN JAVA

CS Week 13. Jim Williams, PhD

A Paradigm (para-dime) is a framework containing the basic assumptions, ways of thinking, and methodology that are commonly accepted by members of a

Part 1: Decimal to Percent. Part 2: Fraction to Percent

CMP-326 Exam 2 Spring 2018 Total 120 Points Version 1

Math Modeling in Java: An S-I Compartment Model

COMP-202 More Complex OOP

Computer Programming: C++

Exam Duration: 2hrs and 30min Software Design

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

DATA TYPES AND EXPRESSIONS

And Even More and More C++ Fundamentals of Computer Science

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Program Fundamentals

(a) in assignment statements. (b) when invoking methods (with objects as parameters) (d) equality of references versus equality of objects

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

Introduction to Programming (Java) 4/12

The Bracket Strategy

CSE 331. Mutation and immutability

Chapter 10 Recursion

Accuplacer Arithmetic Study Guide

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

50 MATHCOUNTS LECTURES (6) OPERATIONS WITH DECIMALS

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

More on inheritance CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Object Oriented Programming

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

MODULE 3q - An Extended Java Object

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CS 247: Software Engineering Principles. ADT Design

CS 302 Week 9. Jim Williams

2.1 Basics of Functions and Their Graphs

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

Topic 6: Inner Classes

An introduction to Java II

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

CHAPTER 7 OBJECTS AND CLASSES

CSC 1214: Object-Oriented Programming

Topic 6: Partial Application, Function Composition and Type Classes

Topic 6: Partial Application, Function Composition and Type Classes

Java and OOP. Part 2 Classes and objects

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

This exam is open book. Each question is worth 3 points.

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 );

Java Magistère BFA

Chapter 4. Defining Classes I

Mini-Lesson 1. Section 1.1: Order of Operations PEMDAS

Transcription:

Object Oriented Design: Building a Fraction Class http://www.zazzle.com/fraction+tshirts Fundamentals of Computer Science

Outline Object oriented techniques Constructors Methods that take another object of same type Private helper methods Fraction class Create a class to represent fractions

Hey objects, where did you come from? "Dude, don't you know where objects come from?!? The object stork totally dropped us off." 0.1, 0.5 r=0.1 0.5, 0.3 r=0.2 0.9, 0.6 r=0.15 public Ball(double x, double y, double r) posx = x; posy = y; radius = r; Constructor = the object stork 3

4 Automatic Default Constructors Rule 1: If you do not create a constructor one will be automatically created for you Default no-arg constructor Doesn't do anything, no code runs All instance variable are whatever you initialized them to (or their default value) private int num; private int denom; // numerator (upstairs) // denominator (downstairs)

5 Creating with Default Constructor To create object using no-arg constructor Use empty ()'s after the new Parameter list always sent when new'ing object Java needs to know which constructor to run Client public static void main(string [] args) Fraction a = new Fraction(); Fraction [] fracs = new Fraction[2]; fracs[0] = new Fraction(); fracs[1] = new Fraction();

6 Declaring Your Own Constructor Rule 2: If you declare any constructor, a default one will not be automatically created private int num; private int denom; // numerator (upstairs) // denominator (downstairs) public Fraction(int n, int d) num = n; denom = d;

Creating with Default Constructor Client public static void main(string [] args) Fraction a = new Fraction(); Fraction [] fracs = new Fraction[2]; fracs[0] = new Fraction(); fracs[1] = new Fraction(); We broke all the calls to create a Fraction object since there no longer exists a no-arg version of the constructor. % javac FractionClient.java FractionClient.java:5: error: constructor Fraction in class Fraction cannot be applied to given types; Fraction a = new Fraction(); ^ required: int,int found: no arguments reason: actual and formal argument lists differ in length 7

Constructor Overloading Rule 3: You can declare as many constructor versions as you need/want Hooray! Now our code using a no-arg constructor will work again. private int num; private int denom; public Fraction() public Fraction(int n, int d) num = n; denom = d; // numerator (upstairs) // denominator (downstairs) 8

Parameters of Your Own Type Create a new object based on another instance of the same type A copy constructor private int num; private int denom; // numerator (upstairs) // denominator (downstairs) // Create a new Fraction object that has the same // values as some other fraction object. public Fraction(Fraction other) num = other.num; denom = other.denom; You can access private instance variables of another object of the same type inside a method of that type. 9

Multiplying Fractions Goal: Given two fraction objects, return a new fraction that is the multiplication of the two Client public static void main(string [] args) Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); Fraction c = a.multiply(b); System.out.println(a + " * " + b + " = " + c); % java FractionClient 1/2 * 2/3 = 1/3 10

Multiply Method private int num; private int denom; // numerator (upstairs) // denominator (downstairs)... public Fraction multiply(fraction other) Fraction result = new Fraction(num * other.num, denom * other.denom); return result; Denominator of the object that called multiply (before the dot). Fraction c = a.multiply(b); Denominator of the object passed as a parameter to the multiply() method 11

12 Multiplying Fractions Attempt 1: Hmmmm, we forgot something Client public static void main(string [] args) Fraction a = new Fraction(1, 2); Fraction b = new Fraction(2, 3); Fraction c = a.multiply(b); System.out.println(a + " * " + b + " = " + c); % java FractionClient Fraction@164f1d0d * Fraction@23fc4bec = Fraction@8dc8569

13 Multiplying Fractions Attempt 2: Close, but not in lowest terms private int num; private int denom; // numerator (upstairs) // denominator (downstairs)... public String tostring() return "" + num + "/" + denom; % java FractionClient 1/2 * 2/3 = 2/6 An object's tostring() method is called automatically whenever you attempt to print an object

14 Lowest Terms Attempt 3: Add code to reduce to lowest terms... public Fraction multiply(fraction other) Fraction result = new Fraction(num * other.num, denom * other.denom); int i = Math.min(Math.abs(result.num), Math.abs(result.denom)); if (i == 0) return result; while ((result.num % i!= 0) (result.denom % i!= 0)) i--; Fraction result2 = new Fraction(result.num / i, result.denom / i); return result2; % java FractionClient 1/2 * 2/3 = 1/3

Divide Method Very similar method for division:... public Fraction divide(fraction other) Fraction result = new Fraction(num * other.denom, denom * other.num); int i = Math.min(Math.abs(result.num), Math.abs(result.denom)); if (i == 0) return result; while ((result.num % i!= 0) (result.denom % i!= 0)) i--; Fraction result2 = new Fraction(result.num / i, result.denom / i); return result2; 15

Repeated Code is Evil public Fraction multiply(fraction other) Fraction result = new Fraction(num * other.num, denom * other.denom); int i = Math.min(Math.abs(result.num), Math.abs(result.denom)); if (i == 0) return result; while ((result.num % i!= 0) (result.denom % i!= 0)) i--; Fraction result2 = new Fraction(result.num / i, result.denom / i); return result2; Where should this code really live? There are a number of choices, but not here for sure. We'd have to repeat it in the divide(), add(), and subtract() methods as well. 16

Helper Methods Add a private helper method, reduce() private void reduce() int i = Math.min(Math.abs(num), Math.abs(denom)); if (i == 0) return; while ((num % i!= 0) (denom % i!= 0)) i--; num = num / i; denom = denom / i; public Fraction multiply(fraction other) Because it is a private method, can only be called inside other methods in the Fraction class Fraction result = new Fraction(num * other.num, denom * other.denom); result.reduce(); return result; 17

Fill in the Missing Code public Fraction multiply(fraction other) Fraction result = new Fraction(num * other.num, result.reduce(); return result; public boolean equals(fraction other) public Fraction reciprocal() public Fraction add(fraction other) denom * other.denom); public Fraction subtract(fraction other) 18

Summary Objects No-arg default constructors Passing objects of same type to method Private helper methods Fraction object Built an object to represent a fraction