0% found this document useful (0 votes)
4 views14 pages

06 Overloading

The document provides an overview of method and constructor overloading in Java, explaining that overloading allows multiple methods with the same name but different signatures within a class. It also discusses the implications of automatic type conversion, access control, static members, and the use of the final keyword. Additionally, it highlights the importance of constructors, including no-argument constructors, and the rules governing access specifiers in Java.

Uploaded by

goyalmadhav196
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views14 pages

06 Overloading

The document provides an overview of method and constructor overloading in Java, explaining that overloading allows multiple methods with the same name but different signatures within a class. It also discusses the implications of automatic type conversion, access control, static members, and the use of the final keyword. Additionally, it highlights the importance of constructors, including no-argument constructors, and the rules governing access specifiers in Java.

Uploaded by

goyalmadhav196
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

26-09-2025

Overloading

Overloading
• Overloading is when two or more methods in
the same class have the same method name
• To be valid, any two definitions of the method
name must have different signatures
▪ A signature consists of the name of a method
together with its parameter list
▪ Differing signatures must have different numbers
and/or types of parameters
• Method Overloading supports polymorphism
because it is one way that Java implements the
“one interface, multiple methods”

4-2

1
26-09-2025

Overloading
// Demonstrate method overloading.
class Overload {
class OverloadDemo {
public static void main(String args[]) {
void test() { OverloadDemo ob = new OverloadDemo();
[Link]("No parameters"); double result;
}
// call all versions of test()
[Link]();
// Overload test for one integer parameter.
[Link](10);
void test(int a) { [Link](10, 20);
[Link]("a: " + a); result = [Link](123.25);
} [Link]("Result of
[Link](123.25): " + result);
}
// Overload test for two integer parameters.
}
void test(int a, int b) {
[Link]("a and b: " + a + " " + b);
} Output:

// overload test for a double parameter


double test(double a) {
[Link]("double a: " + a);
return a*a;
}
} 4-3

Overloading and Automatic Type Conversion

• If Java cannot find a method signature that exactly


matches a method invocation, it will try to use automatic
type conversion

• In some cases of overloading, because of automatic type


conversion, a single method invocation can be resolved in
multiple ways
▪ Ambiguous method invocations will produce an error in Java

4-4

2
26-09-2025

Overloading and Automatic Type Conversion

/* Automatic type conversions apply to


overloading.*/ class Overload {
public static void main(String args[]) {
class OverloadDemo {
OverloadDemo ob = new OverloadDemo();
void test() { int i = 88;
[Link]("No parameters");
} [Link]();
[Link](10, 20);
// Overload test for two integer parameters.
[Link](i); // this will invoke test(double)
void test(int a, int b) { [Link](123.2); // this will invoke test(double)
[Link]("a and b: " + a + " " + b); }
} }

/* overload test for a double parameter and


return type*/
void test(double a) { Output:
[Link]("Inside test(double) a: "
+ a); No parameters
} a and b: 10 20
} Inside test(double) a: 88.0
Inside test(double) a: 123.2

4-5

Pitfall: You Can Not Overload Based on the Type


Returned
• The signature of a method only includes the
method name and its parameter types
▪ The signature does not include the type returned

• Java does not permit methods with the same name


and different return types in the same class

4-6

3
26-09-2025

You Can Not Overload Operators in Java

• Although many programming languages, such as


C++, allow you to overload operators (+, -, etc.),
Java does not permit this
▪ You may only use a method name and ordinary method
syntax to carry out the operations you desire

4-7

Overloading Constructors
class Box {
double width;
double height;
double depth;

// This is the constructor for Box.


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

4
26-09-2025

Include a No-Argument Constructor


• If you do not include any constructors in your class, Java will
automatically create a default or no-argument constructor that
takes no arguments, performs the default initializations, and allows
the object to be created

• If you include even one constructor in your class, Java will not
provide this default constructor

• The following statement is currently invalid:


Box ob = new Box(); //invalid statement

• If you include any constructors in your class, be sure to provide


your own no-argument constructor as well

4-9

Overloading Constructors
/* Here, Box defines three constructors to /* constructor used when no dimensions
initialize the dimensions of a box specified*/
various ways.*/ Box() {
width = -1; // use -1 to indicate
class Box { height = -1; // an uninitialized
double width; depth = -1; // box
}
double height;
double depth; // constructor used when cube is created
Box(double len) {
/* constructor used when all dimensions width = height = depth = len;
specified*/ }
Box(double w, double h, double d) {
// compute and return volume
width = w;
double volume() {
height = h; return width * height * depth;
depth = d; }
} }

5
26-09-2025

Overloading Constructors
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);

double vol;

// get volume of first box


vol = [Link]();
[Link]("Volume of mybox1 is " + vol);

// get volume of second box


vol = [Link]();
[Link]("Volume of mybox2 is " + vol); Output:

// get volume of cube


vol = [Link]();
[Link]("Volume of mycube is " + vol);
}
}

Overloading Constructors – using this


public class Box {
double width;
double height;
double depth;
Box(){
this(-1,-1,-1);
}
Box(Box ob){
this([Link],[Link],[Link]);
}
Box(double len){
this(len,len,len);
}
Box(double w, double h, double d){
width = w;
height = h;
depth = d;
}
double volume(){
[Link]("Inside Box volume");
return width * height * depth;
}

6
26-09-2025

Overloading Constructors – using this


class OverloadCons { // get volume of cube
public static void main(String args[]) { vol = [Link]();
// create boxes using the various constructors [Link]("Volume of mycube is " + vol);
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(); // get volume of myclone
vol = [Link]();
Box mycube = new Box(7); [Link]("Volume of myclone is " +
Box myclone = new Box(mybox1); vol);
}
double vol; }

// get volume of first box


vol = [Link]();
[Link]("Volume of mybox1 is " + vol); Output:

Volume of mybox1 is 3000.0


// get volume of second box
Volume of mybox2 is -1.0
vol = [Link](); Volume of mycube is 343.0
[Link]("Volume of mybox2 is " + vol); Volume of myclone is 3000.0

Recursion
• Recursion is the process of defining something in terms of
itself.

• A method that calls itself is said to be recursive.

• The main advantage to recursive methods is that they can be


used to create clearer and simpler versions of several
algorithms than the iterative methods

• When writing recursive methods, you must have an if


statement somewhere to force the method to return without
the recursive call being executed. If you don’t do this, once
you call the method, it will never return.

• Java supports recursion.

7
26-09-2025

Recursion
// A simple example of recursion. Output:
class Factorial {
// this is a recusive function
int fact(int n) {
int result;

if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}

class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();

[Link]("Factorial of 3 is " + [Link](3));


[Link]("Factorial of 4 is " + [Link](4));
[Link]("Factorial of 5 is " + [Link](5));
}
}

Access Control
• How a member can be accessed is determined by
the access specifier that modifies its declaration

• An access specifier precedes the rest of a


member’s type specification. That is, it must begin
a member’s declaration statement

• There are two levels of access control:


▪ At the top level – public, or package-private (default or no
explicit modifier).
▪ At the member level – public, private, protected,
or package-private (no explicit modifier).

8
26-09-2025

Access Control
• Java’s access specifiers are
• public
• private
• protected (when inheritance is involved)
• default (when no access specifier is used)
– The member is public within its own package but
can’t be accessed outside of its package
– Also known as package-private
• An access specifier precedes the rest of a
member’s type specification. That is, it must begin
a member’s declaration statement

Top level – public and private Modifiers

• A class may be declared with the modifier public,


in which case that class is visible to all classes
everywhere.

• If a class has no modifier (the default, also known


as package-private), it is visible only within its own
package

9
26-09-2025

Member level – public and private Modifiers


• public
▪ no restrictions on where an instance variable or method
can be used

• private
▪ an instance variable or method cannot be accessed by
name outside of the class

• A good programming practice to make all instance


variables private

• Most methods are public, and thus provide


controlled access to the object

• Usually, methods are private only if used as


helping methods for other methods in the class

public and private Modifiers


/* This program demonstrates the class AccessTest {
difference between public and public static void main(String args[]) {
private. Test ob = new Test();
*/
class Test { // These are OK, a and b may be accessed directly
int a; // default access ob.a = 10;
public int b; // public access ob.b = 20;
private int c; // private access
// This is not OK and will cause an error
// methods to access c // ob.c = 100; // Error!
void setc(int i) { // set c's value
c = i; // You must access c through its methods
} [Link](100); // OK

int getc() { // get c's value [Link]("a, b, and c: " + ob.a + " " +
return c; ob.b + " " + [Link]());
} }
} }

Output is:
a, b, and c: 10 20 100

10
26-09-2025

Understanding static
• Used to create a member that can be used by
itself, without reference to a specific instance

• To create such a member, precede its declaration


with the keyword static

• Can be used with both methods and variables

Static instance variables


• Instance variables declared as static are
essentially global variables
▪ When objects of its class are declared, no copy of
static variable is made
▪ All instances of the class share the same static
variable

11
26-09-2025

Static methods
• Methods declared as static have several
restrictions:
• They can only call other static methods
• They must only access static data
• They cannot refer to this or super in any
way
– super relates to the concept of inheritance
• Initialize the static variables using a static
block that gets executed exactly once, when the
class is first loaded

Understanding static
// Demonstrate static variables, methods, and
blocks.
class UseStatic {
static int a = 3;
static int b;

static void meth(int x) { •As soon as the UseStatic class


[Link]("x = " + x); is loaded, all of the static
[Link]("a = " + a); statements are run.
[Link]("b = " + b); 1. First, a is set to 3, then the
} static block executes
(printing a message), and
static { finally, b is initialized to a * 4
[Link]("Static block initialized."); or 12.
b = a * 4; 2. Then main( ) is called, which
} calls meth( ), passing 42 to
x. The three println( )
public static void main(String args[]) { statements refer to the two
meth(42);
static variables a and b, as
well as to the local variable
}
x.
}

12
26-09-2025

Understanding static
• To access the static members, specify the name of
their class followed by the dot operator
[Link]()

Understanding static
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
[Link]("a = " + a);
}
}

class StaticByName {
public static void main(String args[]) {
[Link]();
[Link]("b = " + StaticDemo.b);
}
}

13
26-09-2025

Keyword final
• A variable can be declared as final
• Doing so prevents its contents from being
modified i.e. used as a constant
• Initialize a final variable when it is being declared
final int FILE_NEW = 1 ;
final int FILE_OPEN = 2 ;
• Can also be applied to methods
▪ Used in inheritance

14

You might also like