Questions
This presentation is the property of its rightful owner.
Sponsored Links
1 / 35

Questions? PowerPoint PPT Presentation


  • 82 Views
  • Uploaded on
  • Presentation posted in: General

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

Download Presentation

Questions?

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Questions

Questions?

  • Math Class

  • Wrapper Classes

  • Writing / Testing Methods


Today in comp 110

Today in COMP 110

  • Review

    • Math class / Wrapper classes / Decomposition

    • Calling methods

  • Overloading

  • Programming Demo


The math class

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

Wrapper Classes

  • Each primitive type has an associated “Wrapper” class

    • Byte

    • Short

    • Integer

    • Long

    • Float

    • Double

    • Character

    • Boolean


Writing methods

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

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 methods1

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

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 methods1

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)


Input to methods2

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

Methods that Return a Value

public class Account {

private double balance;

private double limit;

//a helper method to determine if a transaction is valid

privateboolean 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

Method Calls in If-Statements

public class Account {

private double balance;

private double limit;

//a helper method to determine if a transaction is valid

privateboolean 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

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");


Overloading

Overloading


Overloading1

public class InputOne {

public void readInput() {

}

}

public class InputTwo {

public void readInput() {

}

}

Overloading

  • Methods in different classes can have the same name

  • 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

  • }


Overloading2

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

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

}

}


Overloading3

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

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


Overloading4

Overloading

  • Any kind of method can be overloaded

    • Void methods

    • Methods returning a value

    • Static methods

    • Non-static methods

    • Constructors


Constructor overloading

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

Method Signatures

  • A method’s signature consists of

    • 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 signatures1

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

    float getAverage(float a, float b)

    double getAverage(double a, double b)


Automatic type conversion

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

Interaction with Overloading

  • 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);

    }

    }

Which method is being called?


Overloading type conversion

Overloading/Type Conversion

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


Exact overloading match

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

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 calls1

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

}

}


In summary

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

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

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

Room Occupancy

  • Attributes

    • 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 demo1

Programming Demo

  • Programming


Wednesday

Wednesday

  • Array Basics


  • Login