Questions? Math Class Wrapper Classes Writing / Testing Methods.

Slides:



Advertisements
Similar presentations
COMP 110: Introduction to Programming Tyler Johnson Mar 23, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Advertisements

AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
1 COMP 110 Static Methods and Variables Tabitha Peck M.S. March 24, 2008 MWF 3-3:50 pm Philips 367.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
Review Java.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Applications in Java Towson University *Ref:
Java Fundamentals Expanded SE1021 Dr. Mark L. Hornick 1.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
1. 2 Reference... Student stu; Reference of Student stu When the reference is created it points to a null value. Before access the reference, objects.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
COMP 110 Constructors Luv Kohli October 13, 2008 MWF 2-2:50 pm Sitterson 014.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Defining Classes II. Today’s topics  Static methods  Static variables  Wrapper classes  References  Class parameters  Copy constructor.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CSC 142 Computer Science II Zhen Jiang West Chester University
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Catie Welsh March 23,  Lab 6 due Friday by 1pm 2.
COMP 110 Static variables and methods Luv Kohli October 29, 2008 MWF 2-2:50 pm Sitterson 014.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Method OverloadingtMyn1 Method overloading Methods of the same name can be declared in the same class, as long as they have different sets of parameters.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
Exam Review 10/01/2014 Happy October. The Exam  Will be in Canvas  Two parts  Part A is recall – closed book, closed notes ◦Quizzes, in class activity.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
Comp1004: Building Better Objects I Methods. Coming up Methods and Parameters – Why Parameterise? – Call by value, call by reference Return Types – Methods.
Chapter 5 Methods. 2 Contents 1. Introduction to Methods 2. Passing Arguments to a Method 3. More about Local Variables 4. Returning a Value from a Method.
More About Objects and Methods
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Static Members and Methods
Yanal Alahmad Java Workshop Yanal Alahmad
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
More About Objects and Methods
Computer Programming Methodology Input and While Loop
Methods and Parameters
CMSC 202 Static Methods.
CSC240 Computer Science III
Defining Classes II.
Java so far Week 7.
Classes and Objects 5th Lecture
Java Classes and Objects 3rd Lecture
More on Classes and Objects
More About Objects and Methods
Recap Week 2 and 3.
slides created by Ethan Apter
METHODS, CLASSES, AND OBJECTS A FIRST LOOK
Classes and Objects Static Methods
Announcements Lab 5 was due today Program 3 due Monday by 12pm
Java’s Central Casting
Today in COMP 110 Brief static review The Math Class Wrapper Classes
Happy October Exam Review 10/01/2014.
Methods/Functions.
Presentation transcript:

Questions? Math Class Wrapper Classes Writing / Testing Methods

Today in COMP 110 Review Overloading Programming Demo Math class / Wrapper classes / Decomposition Calling methods Overloading Programming Demo

The Math Class Provides many standard mathematical methods All methods are static, no need for an object of the Math class Call methods of the Math class using class name Math.abs Math.max Math.min Math.pow Math.round Others Predefined constants Math.PI Math.E

Wrapper Classes Each primitive type has an associated “Wrapper” class Byte Short Integer Long Float Double Character Boolean

Writing Methods Solving a problem using decomposition Divide into subproblems (pseudocode) Solve each subproblem separately as a method Use the methods you’ve created to solve the problem

Calling Methods within Methods It’s possible to call methods within other methods If calling a method of the same class, no need to specify receiving object public class Example { public void method1() { method2(); //no object needed, current object assumed } public void method2() { //do something

Calling Methods within Methods public class Example { public void method1() { System.out.println("method1!"); method2(); //no object needed, current object assumed } public void method2() { System.out.println("method2!"); public static void main(String[] args) { Example example = new Example(); //create object of class Example example.method1();

Input to Methods The input to a method is in the form of arguments public class Account { private double balance; private double limit; public void addPurchase(double amount) { if(balance + amount <= limit) balance = balance + amount; //only add if the transaction //is valid } The value is filled in by whomever calls the method

Input to Methods A Driver program (Used for testing) public class Account { private double balance; private double limit; public void addPurchase(double amount) { if(balance + amount <= limit) balance = balance + amount; //only add if the transaction is valid } public class AccountTester { public static void main(String[] args) { Account accnt = new Account(); account.addPurchase(15.); //call addPurchase and w/ 15 for the amount account.addPurchase(20.); //call addPurchase and w/ 20 for the amount Separate Java Files! A Driver program (Used for testing)

Input to Methods NEVER do this public class Account { private double balance; private double limit; public void addPurchase(double amount) { Scanner keyboard = new Scanner(System.in); amount = keyboard.nextDouble(); if(balance + amount <= limit) balance = balance + amount; //only add if the transaction is valid } Overwriting the value that was passed in!

Methods that Return a Value public class Account { private double balance; private double limit; //a helper method to determine if a transaction is valid private boolean transactionValid(double amount) { if(balance + amount <= limit) return true; else return false; } public void addPurchase(double amount) { boolean valid = transactionValid(amount); //is the transaction valid? if(valid) balance = balance + amount; //only add if the transaction is valid

Method Calls in If-Statements public class Account { private double balance; private double limit; //a helper method to determine if a transaction is valid private boolean transactionValid(double amount) { if(balance + amount <= limit) return true; else return false; } public void addPurchase(double amount) { if(transactionValid(amount)) balance = balance + amount; //only add if the transaction is valid Call to a method inside an if-statement

Booleans There’s no need to write if(systemsGo == true) System.out.println("Launch"); if(transactionValid(amount) == true) System.out.println("Accepted"); The more concise and equivalent way is if(systemsGo) if(transactionValid(amount))

Overloading

Overloading Methods in different classes can have the same name public class InputOne { public void readInput() { … } public class InputTwo { public void readInput() { … } public static void main(String[] args) { InputOne iOne = new InputOne(); InputTwo iTwo = new InputTwo(); iOne.readInput(); //readInput method of class InputOne iTwo.readInput(); //readInput method of class InputTwo }

Overloading Methods in the same class can also have the same name This is called overloading Distinguished by the number & types of the parameters

Overloading Example public class Average { //average two values public double getAverage(double a, double b) { return (a + b) / 2.; } //average three values public double getAverage(double a, double b, double c) { return (a + b + c) / 3.;

Overloading You have already been using overloaded methods System.out.print(7); //print an integer System.out.print('7'); //print a character System.out.print("seven"); //print a string System.out.print(7.0); //print a double

Other Overloading Examples The Math class double Math.max(double a, double b) int Math.max(int a, int b) long Math.max(long a, long b) Allows the following int m = Math.max(1,3); double d = Math.max(5.6, 5.7);

Overloading Any kind of method can be overloaded Void methods Methods returning a value Static methods Non-static methods Constructors

Constructor Overloading Pet myPet = new Pet(); Pet myPet = new Pet("Fang", 12, 10.); public class Pet { private String name; private int age; private double weight; public Pet() { name = “No name yet.”; age = 0; weight = 0; } public Pet(String initName, int initAge, double initWeight) { name = initName; age = initAge; weight = initWeight;

Method Signatures A method’s signature consists of Example Method name Number of parameters Types of parameters Example public double getAverage(double a, double b) { … } Signature Name: getAverage NumParams: 2 Param Types: Param1: double Param2: double Return type is NOT considered part of the signature!

Method Signatures Java does not allow you to define two methods with the same signature in the same class Examples //these two are the same float getAverage(float a, float b) double getAverage(float a, float b) //these two are different double getAverage(double a, double b)

Automatic Type Conversion Recall that automatic type conversion can sometimes occur with method calls double square(double x) { return x*x; //square the argument and return it } We can call this method as follows square(7.0); //returns 49.0 square(7); //also returns 49.0, auto type conversion

Interaction with Overloading The situation gets more complicated with overloading public class Example { double square(double x) { return x*x; } int square(int x) { public static void main(String[] args) { Example e = new Example(); e.square(7.0); e.square(7); Which method is being called?

Overloading/Type Conversion Java will always use a method that is an exact match before it attempts type conversion

Exact Overloading Match public void example(int i, double d, char c) {…} Are these calls to example an exact match? example(23, 55, 'c'); example(88, 76.0, ';'); example(4.0, 25, '!'); No. Automatic type conversion used Yes. No need for Automatic type conversion No. Automatic type conversion not possible

Ambiguous Method Calls Java will only perform type conversion if the method call is unambiguous There is only ONE method for which automatic type conversion can be used to find a match

Ambiguous Method Calls public class Example { double sum(int a, double b) { return a + b; } double sum(double a, int b) { public static void main(String[] args) { Example e = new Example(); e.sum(7, 7); //error, this method call is ambiguous e.sum(7, 7.0); //this is ok e.sum(7.0, 7); //this is ok

In Summary How Java determines which method you intend to call Match Based on Method Name, Num & Types of Parameters Exact Match? Use the Method Unambiguous Match using Type Conversion? Use the Method Error

Use of Overloading Misuse of overloading can lead to strange bugs Use only with good reason public Pet(double initWeight) { //constructor for weight weight = initWeight; } public Pet(int initAge) { //constructor for age age = initAge; public static void main(String[] args) { Pet myPet = new Pet(65); //meant to set weight, set age instead

Programming Demo Room Occupancy Create a class called Room that can be used to record the number of people in the rooms of a building

Room Occupancy Attributes Methods numberInRoom – the number of people in a room totalNumber – the total number of people in all rooms as a static variable Methods default constructor – sets number of people in room to 0 addOneToRoom – add a person to the room removeOneFromRoom – remove a person from the room (don’t go below 0 persons) getNumber – returns the number of people in the room getTotal – a static method that returns the total number of people in all rooms validRemoval(int num) – returns whether num people can be removed from the room

Programming Demo Programming

Wednesday Array Basics