Method Overloading.. Method Overloading Can two methods in a class have the same name? Two methods in a class can have the same name provided – they take.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
CS 106 Introduction to Computer Science I 11 / 09 / 2007 Instructor: Michael Eckmann.
Lecture 2 Classes and objects, Constructors, Arrays and vectors.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
Metode di Java Risanuri Hidayat, Ir., M.Sc.. Pendahuluan Classes usually consist of two things: instance variables and methods. The topic of methods is.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
More on Objects CS 102 More, more, more on Objects.
1 Overloading vs. Overriding b Don't confuse the concepts of overloading and overriding b Overloading deals with multiple methods in the same class with.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
Lecture From Chapter 6 & /8/10 1 Method of Classes.
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
NSIT,Jetalpur CORE JAVA CONCEPTS SURABHI MISHRA (LCE)NSIT.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
1 Software Construction Lab 4 Classes and Objects in Java Basics of Classes in Java.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
28-Dec-04polymorhism.ppt1 Polymorphism. 28-Dec-04polymorhism.ppt2 signatures in any programming language, a signature is what distinguishes one function.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
ECE122 Feb. 22, Any question on Vehicle sample code?
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
What is an Object? Real world objects are things that have: 1) state 2) behavior Example: your dog: 1) state – name, color, breed, sits?, barks?, wages.
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.
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
Classes and Methods. Classes Class Definition Data Fields –Variables to store data items –Differentiate multiple objects of a class –They are called.
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.
L EC. 06: C LASS D ETAILS (2/2) S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length.
CSI 3125, Preliminaries, page 1 Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name,
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.
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.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
C# Programming Methods.
1 Class and Object Lecture 7. 2 Classes Classes are constructs that define objects of the same type. A Java class uses instance variables to define data.
Method overloading contd class OverloadDemo { public static void main(String args[]) { Overload ob = new Overload(); int resI; double resD; // call all.
Classes - Intermediate
COME 339 WEEK 1. Example: The Course Class 2 TestCourceRunCourse.
AP Computer Science A – Healdsburg High School 1 Unit 9 - Parameter Passing in Java.
Utilities (Part 2) Implementing static features 1.
Programming Languages -2 C++ Lecture 3 Method Passing Function Recursion Function Overloading Global and Local variables.
Methods What is a method? Main Method the main method is where a stand alone Java program normally begins execution common compile error, trying.
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
Methods and Classes. Method Overloading Two or more methods within the same class that share the same name but different parameters class OverloadDemo.
Functions Modules in C++ are called functions and classes. Main reason to use functions is : – get aid in conceptual organization.
Recursion occurs when a method calls itself. public class RecursionOne { public void run(int x) { System.out.println(x); run(x+1); } public static void.
Staples are our staple Building upon our solution.
OOP Features Object Oriented Programming Main issues in software engineering – –maintainability, reusability, portability, security, integrity, user.
Defining Your Own Classes II
Some Assignments  Write a program which prints the following information about at least 5 persons: NAME MAIL-ID EMPLOYEE-CODE PHONE Eg. Umesh
Static data members Constructors and Destructors
An Introduction to Java – Part I, language basics
Group Status Project Status.
Cs212: DataStructures Computer Science Department Lab 3 : Recursion.
Method Overloading in JAVA
JAVA Constructors.
Chapter 6 Methods.
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
JAVA 22 February 2019 DEPARTMENT OF CSE.
Method of Classes Chapter 7, page 155 Lecture /4/6.
Review of Previous Lesson
Class.
Class: Special Topics Overloading (methods) Copy Constructors
Corresponds with Chapter 5
Introduction to Methods and Interfaces
Presentation transcript:

Method Overloading.

Method Overloading Can two methods in a class have the same name? Two methods in a class can have the same name provided – they take different numbers of arguments, or – the type of at least one argument is different This is called method overloading. Why is this useful?

Method Overloading The compiler does not consider return type when differentiating methods We cannot declare two methods with the same signature even if they have a different return type. public int countRows(int number); public String countRows(int number); public String printString(String string) public String printString(String string, int offset)

Example public class MainClass { public void print(int a) { System.out.println(a); } public void print(String a) { System.out.println(a); } }

Example public class DataArtist {... public void draw(String s) {... } public void draw(int i) {... } public void draw(double f) {... } public void draw(int i, double f) {... } }

Overloaded Methods public class Circle { public void move (int x, int y) {... } public void move (Point p) {... }... Circle circle = new Circle(5); circle.move (50, 100); Point center = new Point(50, 100); circle.move (center); The compiler treats overloaded methods as completely different methods. The compiler knows which one to call based on the number and the types of the parameters passed to the method.

Multiple Constructors Constructors can be overloaded. If a class has more than one constructor, they must have different numbers and/or types of parameters.

Example public class Fraction { private int num, denom; public Fraction ( ) { num = 0; denom = 1; } public Fraction (int n) { num = n; denom = 1; } public Fraction (int n, int d) { num = n; denom = d; reduce (); }

Calling a Constructor from a Constructor Constructors of a class can call each other using the keyword this — a good way to avoid duplicating code: public class Fraction {... public Fraction (int n) { this (n, 1); }... public Fraction (int p, int q) { num = p; denom = q; reduce (); }...

Example class Sphere { // Construct a unit sphere at the origin Sphere() { radius = 1.0; ++count; } Sphere(double x, double y, double z) { this(); // Call the constructor with no arguments xCenter = x; yCenter = y; zCenter = z; } Sphere(double theRadius, double x, double y, double z) { this(x, y, z); radius = theRadius; } // The rest of the class as before... }

Example class OverloadDemo { void test() { System.out.println(“No Parameters”); } void test (int a) { System.out.println(“a: “ + a); } void test (int a, int b) { System.out.println(“a and b: “ + a+ “ “ +b); } double test(double a) { System.out.println(“double a: ”+a); return a*a; }

Example class Overload { public static void main (String args[]) { OverloadDemo ob = new OverloadDemo () ; double result; ob.test(); ob.test(10); ob.test(10,20); result = ob.test (123.25); System.out.println(“Result of ob.test(123.2): “ + result); }

Recursion A method that calls itself is described as a recursive method, and The process is referred to as recursion. You can also have indirect recursion where a method A calls another method B, which in turn calls the method A. Clearly you must include some logic in a recursive method so that it will eventually stop calling itself if the process is not to continue indefinitely.

Recursion Example You can write a method that will calculate integer powers of a variable—in other words, evaluate x n, or x*x...*x where x is multiplied by itself n times. You can use the fact that you can obtain x n by multiplying x n -1 by x. Example You can calculate 2 4 as 2 3 multiplied by 2, and you can get 2 3 by multiplying 2 2 by 2, and 2 2 is produced by multiplying 2 1, which is 2, of course, by 2.

Recursion Example public class PowerCalc { public static void main(String[] args) { double x = 5.0; System.out.println(x + “ to the power 4 is “ + power(x,4)); System.out.println(“7.5 to the power 5 is “ + power(7.5,5)); System.out.println(“7.5 to the power 0 is “ + power(7.5,0)); System.out.println(“10 to the power -2 is “ + power(10,-2)); } // Raise x to the power n static double power(double x, int n) { if(n > 1) return x*power(x, n-1); // Recursive call else if(n < 0) return 1.0/power(x, -n); // Negative power of x else return n == 0 ? 1.0 : x; // When n is 0 return 1, otherwise x }

Recursion Example This program will produce the following output: 5.0 to the power 4 is to the power 5 is to the power 0 is to the power -2 is 0.01

Recursion Example You can see from this that the power() method is called four times in all. The calls cascade down through four levels until the value of n is such that it allows a value to be returned. The return values ripple up through the levels until you are eventually back at the top, and is returned to the original calling point.

Lab Practice Compile & execute “Overload” & “OverloadDemo” classes Examine its output.

Lab Practice Rewrite “Employee” & “EmployeeDemo” using overloaded constructors such as; Employee(); Employee (String, int, double); Employee(String, int); Create 2 Employee objects & Initialize data members of Employee class for each object through constructor. Compile n execute the code and examine its output.