Overloading. Overloading Basics  We have seen that you can give the same name to methods in different classes.  You can also give the same name to methods.

Slides:



Advertisements
Similar presentations
Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS
Advertisements

Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
CSCI S-1 Section 5. Deadlines for Problem Set 3 Part A – Friday, July 10, 17:00 EST Parts B – Tuesday, July 14, 17:00 EST Getting the code examples from.
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Transition from C++ to Java Walt Savitch University of California, San Diego
Overloading methods review When is the return statement required? What do the following method headers tell us? public static int max (int a, int b)
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
Constructors. Defining Constructors  A constructor is a special kind of method that is designed to perform initializations, such as giving values to.
Information Hiding and Encapsulation
Introduction to Computer Programming Classy Programming Techniques II: Writing Objects.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
Scanner & Stepwise Refinement Pepper With credit to Dr. Siegfried.
1 Scanner objects. 2 Interactive programs We have written programs that print console output. It is also possible to read input from the console.  The.
Warm-Up: Monday, March 3 List all devices you can think of that can be used to input information into the computer.
Intro to Java Programming  A computer follows the instruction precisely and exactly.  Anything has to be declared and defined before it can be used.
Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Starting Out with Java: From Control Structures through Objects
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Chapter 2 Console Input and Output Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Sahar Mosleh California State University San MarcosPage 1 System.out.println for console output System.out is an object that is part of the Java language.
Slides prepared by Rose Williams, Binghamton University Chapter 2 Console Input and Output.
More About Objects and Methods Chapter 5. When an Object Is Required Methods called outside the object definition require an object to precede the method.
COMP 110 Constructors Luv Kohli October 13, 2008 MWF 2-2:50 pm Sitterson 014.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
The String Class A String is an object. An object is defined by a class. In general, we instantiate a class like this: String myString = new String(“Crazy.
Day Class Definitions and Methods Local & global variables, parameters & arguments,
CSC 142 Computer Science II Zhen Jiang West Chester University
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
Component 4: Introduction to Information and Computer Science Unit 5: Overview of Programming Languages, Including Basic Programming Concepts Lecture 3.
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.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
FOR LOOP WALK THROUGH public class NestedFor { public static void main(String [] args) { for (int i = 1; i
Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void.
Catie Welsh March 23,  Lab 6 due Friday by 1pm 2.
Methods OR HOW TO MAKE A BIG PROGRAM SEEM SMALLER.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Polymorphism l Constructors.
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.
COMP 110 Designing and overloading methods Luv Kohli November 3, 2008 MWF 2-2:50 pm Sitterson 014.
Methods.
AP Computer Science A – Healdsburg High School 1 Unit 9 - Parameter Passing in Java.
Lecture 10: Object Oriented Programming Tami Meredith.
Computer Programming Lab 9. Exercise 1 Source Code package excercise1; import java.util.Scanner; public class Excercise1 { public static void main(String[]
Methods What is a method? Main Method the main method is where a stand alone Java program normally begins execution common compile error, trying.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Introduction to programming in java
CompSci 230 S Programming Techniques
Arrays in Classes and Methods
Something about Java Introduction to Problem Solving and Programming 1.
Java so far Week 7.
Questions? Math Class Wrapper Classes Writing / Testing Methods.
Method Overloading in JAVA
The Basics of Recursion
class PrintOnetoTen { public static void main(String args[]) {
Scope of variables class scopeofvars {
Announcements Lab 5 was due today Program 3 due Monday by 12pm
Basic Exception Handling
Programming with Arrays 1
More About Objects and Methods Chapter 5 Programming with Methods
Presentation transcript:

Overloading

Overloading Basics  We have seen that you can give the same name to methods in different classes.  You can also give the same name to methods within the same class.  This is called overloading.  In order for this to work there must be something different about the parameter lists to the two methods.

Overloading Basics (cont’d)  For example, one method may have three parameters, another with the same name may have only two parameters, and yet another may have parameters of a different type.  When Java encounters the invocation of a method name which may have different definitions, it selects the one for which the arguments in the invocation match the number and types of the parameters in the method definition.

Overloading Basics (cont’d)  If Java cannot find a method which exactly matches the types of the arguments, it will try to make some simple type conversions.  The Math class uses overloading for some of its methods.  That is, it decides which version of a method to use based on the types of the arguments.

Overloading Example  /** This is just a toy class to illustrate overloading. */ public class Statistician { public static void main(String[] args) { double average1 = Statistician.average(40.0, 50.0); double average2 = Statistician.average(1.0, 2.0, 3.0); char average3 = Statistician.average('a', 'c'); System.out.println("average1 = " + average1); System.out.println("average2 = " + average2); System.out.println("average3 = " + average3); } public static double average(double first, double second) { return ((first + second)/2.0); } public static double average(double first, double second, double third) { return ((first + second + third)/3.0); } public static char average(char first, char second) { return (char)(((int)first + (int)second)/2); } }

Another Overloading Example Pet - name: String - age: int - weight: double + writeOutput(): void + set(String newName): void + set(int newAge): void + set(double newWeight): void + set(String newName, int newAge, double newWeight): void + getName(): String + getAge(): int + getWeight(): double

Another Overloading Example (cont’d) /** Class for basic pet records: name, age, and weight. */ public class Pet { private String name; private int age; //in years private double weight; //in pounds /** This main is just a demonstration program. */ public static void main(String[] args) { Pet myDog = new Pet( ); myDog.set("Fido", 2, 5.5); myDog.writeOutput( ); System.out.println("Changing name."); myDog.set("Rex"); myDog.writeOutput( ); System.out.println("Changing weight."); myDog.set(6.5); myDog.writeOutput( ); System.out.println("Changing age."); myDog.set(3); myDog.writeOutput( ); }

Another Overloading Example (cont’d) public void writeOutput( ) { System.out.println("Name: " + name); System.out.println("Age: " + age + " years"); System.out.println("Weight: " + weight + " pounds"); } public void set(String newName) { name = newName; //age and weight are unchanged. } public void set(int newAge) { if (newAge <= 0) { System.out.println("Error: invalid age."); System.exit(0); } else age = newAge; //name and weight are unchanged. }

Another Overloading Example (cont’d) public void set(double newWeight) { if (newWeight <= 0) { System.out.println("Error: invalid weight."); System.exit(0); } else weight = newWeight; //name and age are unchanged. } public void set(String newName, int newAge, double newWeight) { name = newName; if ((newAge <= 0) || (newWeight <= 0)) { System.out.println("Error: invalid age or weight."); System.exit(0); } else { age = newAge; weight = newWeight; } }

Another Overloading Example (cont’d) public String getName( ) { return name; } public int getAge( ) { return age; } public double getWeight( ) { return weight; } }

Overloading and Automatic Type Conversion  Java always tries to use overloading before it tries to use automatic type conversion.  If it can find a method definition that matches the argument types it will use that method.  Java will do automatic type conversion only if it fails to match the argument types.

The Money Class Example import java.util.*; /** Objects represent nonnegative amounts of money, such as $100, $41.99, $0.05. */ public class Money { private long dollars; private long cents; public void set(long newDollars) { if (newDollars < 0) { System.out.println( "Error: Negative amounts of money are not allowed."); System.exit(0); } else { dollars = newDollars; cents = 0; } }

The Money Class Example (cont’d) public void set(double amount) { if (amount < 0) { System.out.println( "Error: Negative amounts of money are not allowed."); System.exit(0); } else { long allCents = Math.round(amount*100); dollars = allCents/100; cents = allCents%100; } } public void set(Money otherObject) { this.dollars = otherObject.dollars; this.cents = otherObject.cents; }

The Money Class Example (cont’d) /** Precondition: The argument is an ordinary representation of an amount of money, with or without a dollar sign. Fractions of a cent are not allowed. */ public void set(String amountString) { String dollarsString; String centsString; if (amountString.charAt(0) == '$') //Delete '$' if any amountString = amountString.substring(1); amountString = amountString.trim( ); int pointLocation = amountString.indexOf("."); //Locate decimal point if (pointLocation 99)) { System.out.println( "Error: Illegal representation of money."); System.exit(0); } } }

The Money Class Example (cont’d) public void readInput( ) { System.out.println("Enter amount on a line by itself:"); Scanner keyboard = new Scanner(System.in); String amount = keyboard.nextLine( ); set(amount.trim( )); } /** Does not go to the next line after outputting money. */ public void writeOutput( ) { System.out.print("$" + dollars); if (cents < 10) System.out.print(".0" + cents); else System.out.print("." + cents); }

The Money Class Example (cont’d) /** Returns n times the calling object. */ public Money times(int n) { Money product = new Money( ); product.cents = n*cents; long carryDollars = product.cents/100; product.cents = product.cents%100; product.dollars = n*dollars + carryDollars; return product; } /** Returns the sum of the calling object and the argument. */ public Money add(Money otherAmount) { Money sum = new Money( ); sum.cents = this.cents + otherAmount.cents; long carryDollars = sum.cents/100; sum.cents = sum.cents%100; sum.dollars = this.dollars + otherAmount.dollars + carryDollars; return sum; } }

Example of Using the Money Class public class MoneyDemo { public static void main(String[] args) { Money start = new Money( ); Money goal = new Money( ); System.out.println("Enter your current savings:"); start.readInput( ); goal = start.times(2); System.out.print( "If you double that, you will have "); goal.writeOutput( ); System.out.println(", or better yet:"); goal = start.add(goal); System.out.println( "If you triple that original amount, you will have:"); goal.writeOutput( ); System.out.println( ); System.out.println("Remember: A penny saved"); System.out.println("is a penny earned."); } }