+ All Categories
Home > Documents > Questions?

Questions?

Date post: 08-Jan-2016
Category:
Upload: sora
View: 25 times
Download: 2 times
Share this document with a friend
Description:
Questions?. Math Class Wrapper Classes Writing / Testing Methods. Today in COMP 110. Review Math class / Wrapper classes / Decomposition Calling methods Overloading Programming Demo. The Math Class. Provides many standard mathematical methods - PowerPoint PPT Presentation
35
COMP 110: Spring 2009 1 Questions? Math Class Wrapper Classes Writing / Testing Methods
Transcript
Page 1: Questions?

COMP 110: Spring 20091

Questions?

Math Class

Wrapper Classes

Writing / Testing Methods

Page 2: Questions?

COMP 110: Spring 20092

Today in COMP 110

ReviewMath class / Wrapper classes / DecompositionCalling methods

Overloading

Programming Demo

Page 3: Questions?

COMP 110: Spring 20093

The Math Class

Provides many standard mathematical methodsAll methods are static, no need for an object of the Math class

Call methods of the Math class using class nameMath.absMath.maxMath.minMath.powMath.roundOthers

Predefined constantsMath.PIMath.E

Page 4: Questions?

COMP 110: Spring 20094

Wrapper Classes

Each primitive type has an associated “Wrapper” class

ByteShortIntegerLongFloatDoubleCharacterBoolean

Page 5: Questions?

COMP 110: Spring 20095

Writing Methods

Solving a problem using decomposition

Divide into subproblems (pseudocode)Solve each subproblem separately as a methodUse the methods you’ve created to solve the problem

Page 6: Questions?

COMP 110: Spring 20096

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}

}

Page 7: Questions?

COMP 110: Spring 20097

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

Exampleexample.method1();

}}

Page 8: Questions?

COMP 110: Spring 20098

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

Page 9: Questions?

COMP 110: Spring 20099

Input to Methods

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)

Page 10: Questions?

COMP 110: Spring 200910

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!

Page 11: Questions?

COMP 110: Spring 200911

Methods that Return a Value

public class Account {private double balance;private double limit;

//a helper method to determine if a transaction is validprivate 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}

}

Page 12: Questions?

COMP 110: Spring 200912

Method Calls in If-Statements

public class Account {private double balance;private double limit;

//a helper method to determine if a transaction is validprivate 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

Page 13: Questions?

COMP 110: Spring 200913

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)System.out.println("Launch");

if(transactionValid(amount))System.out.println("Accepted");

Page 14: Questions?

COMP 110: Spring 200914

Overloading

Page 15: Questions?

COMP 110: Spring 200915

Overloading

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

}

•Methods in different classes can have the same name

Page 16: Questions?

COMP 110: Spring 200916

Overloading

Methods in the same class can also have the same name

This is called overloading

Distinguished by the number & types of the parameters

Page 17: Questions?

COMP 110: Spring 200917

Overloading Example

public class Average {

//average two valuespublic double getAverage(double a, double b) { return (a + b) / 2.;}

//average three valuespublic double getAverage(double a, double b, double c) { return (a + b + c) / 3.;}

}

Page 18: Questions?

COMP 110: Spring 200918

Overloading

You have already been using overloaded methods

System.out.print(7); //print an integerSystem.out.print('7'); //print a characterSystem.out.print("seven"); //print a stringSystem.out.print(7.0); //print a double

Page 19: Questions?

COMP 110: Spring 200919

Other Overloading Examples

The Math classdouble Math.max(double a, double b)int Math.max(int a, int b)long Math.max(long a, long b)

Allows the followingint m = Math.max(1,3);double d = Math.max(5.6, 5.7);

Page 20: Questions?

COMP 110: Spring 200920

Overloading

Any kind of method can be overloaded

Void methodsMethods returning a valueStatic methodsNon-static methodsConstructors

Page 21: Questions?

COMP 110: Spring 200921

Constructor Overloading

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

Pet myPet = new Pet();

Pet myPet = new Pet("Fang", 12, 10.);

Page 22: Questions?

COMP 110: Spring 200922

Method Signatures

A method’s signature consists of Method nameNumber of parametersTypes of parameters

Example

public double getAverage(double a, double b) { … }

SignatureName: getAverageNumParams: 2Param Types:

Param1: doubleParam2: double

Return type is NOT considered part of the signature!

Page 23: Questions?

COMP 110: Spring 200923

Method Signatures

Java does not allow you to define two methods with the same signature in the same class

Examples//these two are the samefloat getAverage(float a, float b)double getAverage(float a, float b)

//these two are differentfloat getAverage(float a, float b)double getAverage(double a, double b)

Page 24: Questions?

COMP 110: Spring 200924

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 followssquare(7.0); //returns 49.0square(7); //also returns 49.0, auto type conversion

Page 25: Questions?

COMP 110: Spring 200925

The situation gets more complicated with overloading

public class Example {

double square(double x) { return x*x; }

int square(int x) { return x*x; } public static void main(String[] args) { Example e = new Example(); e.square(7.0); e.square(7); }}

Interaction with Overloading

Which method is being called?

Page 26: Questions?

COMP 110: Spring 200926

Overloading/Type Conversion

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

Page 27: Questions?

COMP 110: Spring 200927

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

Page 28: Questions?

COMP 110: Spring 200928

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

Page 29: Questions?

COMP 110: Spring 200929

Ambiguous Method Calls

public class Example {

double sum(int a, double b) { return a + b; }

double sum(double a, int b) { return a + 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 }}

Page 30: Questions?

COMP 110: Spring 200930

In Summary

How Java determines which method you intend to call

Exact Match?

Use the Method

Unambiguous Match using Type

Conversion?

Use the Method

Error

Match Based on Method Name, Num & Types of

Parameters

Page 31: Questions?

COMP 110: Spring 200931

Use of Overloading

Misuse of overloading can lead to strange bugsUse only with good reason

public Pet(double initWeight) { //constructor for weightweight = initWeight;

}

public Pet(int initAge) { //constructor for ageage = initAge;

}

public static void main(String[] args) {Pet myPet = new Pet(65); //meant to set weight, set age instead

}

Page 32: Questions?

COMP 110: Spring 200932

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

Page 33: Questions?

COMP 110: Spring 200933

Room Occupancy

AttributesnumberInRoom – the number of people in a roomtotalNumber – the total number of people in all rooms as a static variable

Methodsdefault constructor – sets number of people in room to 0addOneToRoom – add a person to the roomremoveOneFromRoom – remove a person from the room (don’t go below 0 persons)getNumber – returns the number of people in the roomgetTotal – a static method that returns the total number of people in all roomsvalidRemoval(int num) – returns whether num people can be removed from the room

Page 34: Questions?

COMP 110: Spring 200934

Programming Demo

Programming

Page 35: Questions?

COMP 110: Spring 200935

Wednesday

Array Basics


Recommended