0% found this document useful (0 votes)
106 views

2 Overloading Methods and Constructors

Method overloading allows methods within the same class to share the same name but have different parameter lists. Java determines which overloaded method to call based on the number and type of arguments passed. Constructors can also be overloaded. Objects are passed by reference, so changes within a method affect the original object, while primitive types like int are passed by value so changes only affect the method parameter, not the original variable.

Uploaded by

Sreshtha Kashyap
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

2 Overloading Methods and Constructors

Method overloading allows methods within the same class to share the same name but have different parameter lists. Java determines which overloaded method to call based on the number and type of arguments passed. Constructors can also be overloaded. Objects are passed by reference, so changes within a method affect the original object, while primitive types like int are passed by value so changes only affect the method parameter, not the original variable.

Uploaded by

Sreshtha Kashyap
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Overloading Methods and

Constructors
Method Overloading

• Two or more methods within the same class


that share the same name but with different
parameter declarations.
• When an overloaded method is invoked, Java
uses the type and/or number of arguments as
its guide to determine which version of the
overloaded method to actually call.
Example
class OverloadDemo { class Overload {
void test() { public static void main(String
System.out.println("No parameters"); args[]) {
} OverloadDemo ob =
// Overload test for one integer parameter. new OverloadDemo();
double result;
void test(int a) {
// call all versions of test()
System.out.println("a: " + a);
ob.test();
} ob.test(10);
// Overload test for two integer parameters. ob.test(10, 20);
void test(int a, int b) { result = ob.test(123.25);
System.out.println("a and b: " + a + " " + b); System.out.println("Result
} of ob.test(123.25): " + result);
// overload test for a double parameter }
double test(double a) { }
System.out.println("double a: " + a);
return a*a;
}
}
Example Explained
• Here, test( ) is overloaded four times.
• The first version takes no parameters, the second takes one
integer parameter, the third takes two integer parameters, and the
fourth takes one double parameter.
• The fact that the fourth version of test( ) also returns a value is of
no consequence relative to overloading, since return types do not
play a role in overload resolution.
• When an overloaded method is called, Java looks for a match
between the arguments used to call the method and the
method’s parameters.
• However, this match need not always be exact.
• In some cases, Java’s automatic type conversions can play a role
in overload resolution.
Automatic Type conversions Example
class OverloadDemo {
class Overload {
void test() {
public static void main(String args[]) {
System.out.println("No parameters"); OverloadDemo ob = new OverloadDemo();
} ob.test();
// Overload test for two integer ob.test(10, 20);
//parameters. // this will invoke test(double)
ob.test(88);
void test(int a, int b) { // this will invoke test(double)
System.out.println("a and b: " + a + " " ob.test(123.2);
+ b); }
} }
// overload test for a double
//parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
Example Explained
• This version of OverloadDemo does not define test(int).
• Therefore, when test( ) is called with an integer argument inside
Overload, no matching method is found.
• However, Java can automatically convert an integer into a double, and
this conversion can be used to resolve the call.
• Therefore, after test(int) is not found, Java elevates i to double and then
calls test(double).
• In languages that do not support method overloading, each method must
be given a unique name.
• However, frequently you will want to implement essentially the same
method for different types of data. Consider the absolute value function.
• In languages that do not support overloading, there are usually three or
more versions of this function, each with a slightly different name.
• For instance, in C, the function abs( ) returns the absolute value of an
integer, labs( ) returns the absolute value of a long integer, and fabs( )
returns the absolute value of a floating-point value.
• Since C does not support overloading, each function has to have its own
name, even though all three functions do essentially the same thing.
Constructor Overloading
/* Here, Box defines three constructors to initialize
class OverloadCons {
the dimensions of a box various ways.*/
class Box { public static void main(String args[]) {
double width; // create boxes using the various constructors
double height; Box mybox1 = new Box(10, 20, 15);
double depth;
// constructor used when all dimensions specified
Box mybox2 = new Box();
Box(double w, double h, double d) { Box mycube = new Box(7);
width = w; double vol;
height = h;
// get volume of first box
depth = d;
} vol = mybox1.volume();
// constructor used when no dimensions specified System.out.println("Volume of mybox1 is "
Box() { + vol);
width = -1; // use -1 to indicate
height = -1; // an uninitialized
// get volume of second box
depth = -1; // box vol = mybox2.volume();
} System.out.println("Volume of mybox2 is " +
// constructor used when cube is created
vol);
Box(double len) {
width = height = depth = len; // get volume of cube
} vol = mycube.volume();
// compute and return volume System.out.println("Volume of mycube is " +
double volume() {
return width * height * depth;
vol);
} }
} }
Using Objects as parameters
// Here, Box allows one object to initialize another. class OverloadCons2 {
class Box { public static void main(String args[]) {
double width; // create boxes using the various constructors
double height; Box mybox1 = new Box(10, 20, 15);
double depth; Box mybox2 = new Box();
// This constructor takes an object of type Box. Box mycube = new Box(7);
Box(Box ob) { // pass object to constructor // create copy of mybox1
width = ob.width; Box myclone = new Box(mybox1);
height = ob.height; double vol;
depth = ob.depth; } // get volume of first box
// constructor used when all dimensions specified vol = mybox1.volume();
Box(double w, double h, double d) { System.out.println("Volume of mybox1 is " + vol);
width = w; // get volume of second box
height = h; vol = mybox2.volume();
depth = d; } System.out.println("Volume of mybox2 is " + vol);
// constructor used when no dimensions specified // get volume of cube
Box() { vol = mycube.volume();
width = -1; // use -1 to indicate System.out.println("Volume of cube is " + vol);
height = -1; // an uninitialized // get volume of clone
depth = -1; // box } vol = myclone.volume();
// constructor used when cube is created System.out.println("Volume of clone is " + vol);
Box(double len) { }
width = height = depth = len; } }
// compute and return volume
double volume() {
return width * height * depth; }
}
Q. Write a program in Java to
demonstrate call by value and call
by reference.

• Hint:
• Primitive types are passed by value
• Objects are passed as reference
Pass by value
// Primitive types are passed by value.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}
}
Pass by reference
// Objects are passed by reference.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
String class
• Every string you create is actually an object of type
String. Even string constants are actually String
objects.
• The second thing to understand about strings is
that objects of type String are immutable; once a
String object is created, its contents cannot be
altered.
– If you need to change a string, you can always create a
new one that contains the modifications.
– Java defines a peer class of String, called StringBuffer,
which allows strings to be altered, so all of the normal
string manipulations are still available in Java.
// Demonstrating Strings.
class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
Input from user
import java.util.Scanner;
public class userInput {
public static void main(String args[]) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}

You might also like