[Go to site: main page, start]

0% found this document useful (0 votes)
13 views10 pages

Java Method Overloading

The document explains Java method overloading, which allows multiple methods with the same name but different parameters, enhancing code readability. It also covers Java constructors, detailing their types (no-arg, parameterized, and default) and the rules for creating them. Additionally, it discusses constructor overloading, where multiple constructors can exist in a class with different parameters.

Uploaded by

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

Java Method Overloading

The document explains Java method overloading, which allows multiple methods with the same name but different parameters, enhancing code readability. It also covers Java constructors, detailing their types (no-arg, parameterized, and default) and the rules for creating them. Additionally, it discusses constructor overloading, where multiple constructors can exist in a class with different parameters.

Uploaded by

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

Java Method Overloading

In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called
overloaded methods and this feature is called method overloading. For example:

void func() { ... }


void func(int a) { ... }

float func(double a) { ... }

float func(int a, float b) { ... }

Here, the func() method is overloaded. These methods have the same name but accept
different arguments.

Note: The return types of the above methods are not the same. It is because method
overloading is not associated with return types. Overloaded methods may have the same or
different return types, but they must differ in parameters.

Why method overloading?

Suppose, you have to perform the addition of given numbers but there can be any number of
arguments (let’s say either 2 or 3 arguments for simplicity).

In order to accomplish the task, you can create two methods sum2num(int,
int) and sum3num(int, int, int) for two and three parameters respectively. However,
other programmers, as well as you in the future may get confused as the behavior of both
methods are the same but they differ by name.
The better way to accomplish this task is by overloading methods. And, depending upon the
argument passed, one of the overloaded methods is called. This helps to increase the
readability of the program.

How to perform method overloading in Java?


Here are different ways to perform method overloading:
1. Overloading by changing the number of parameters

class MethodOverloading {
private static void display(int a){
[Link]("Arguments: " + a);
}

private static void display(int a, int b){


[Link]("Arguments: " + a + " and " + b);
}
public static void main(String[] args) {
display(1);
display(1, 4);
}
}

Output:

Arguments: 1
Arguments: 1 and 4

2. Method Overloading by changing the data type of parameters

class MethodOverloading {

// this method accepts int


private static void display(int a){
[Link]("Got Integer data.");
}

// this method accepts String object


private static void display(String a){
[Link]("Got String object.");
}

public static void main(String[] args) {


display(1);
display("Hello");
}
}

Output:

Got Integer data.


Got String object.

Here, both overloaded methods accept one argument. However, one accepts the argument of
type int whereas other accepts String object.

Let’s look at a real-world example:


class HelperService {

private String formatNumber(int value) {


return [Link]("%d", value);
}

private String formatNumber(double value) {


return [Link]("%.3f", value);
}

private String formatNumber(String value) {


return [Link]("%.2f", [Link](value));
}

public static void main(String[] args) {


HelperService hs = new HelperService();
[Link]([Link](500));
[Link]([Link](89.9934));
[Link]([Link]("550"));
}
}

When you run the program, the output will be:

500
89.993
550.00

Note: In Java, you can also overload constructors in a similar way like methods.

Important Points

 Two or more methods can have the same name inside the same class if they accept

different arguments. This feature is known as method overloading.

 Method overloading is achieved by either:


o changing the number of arguments.

o or changing the data type of arguments.

 It is not method overloading if we only change the return type of methods. There must be

differences in the number of parameters.

Java Constructors
A constructor in Java is similar to a method that is invoked when an object of the class is
created.
Unlike Java methods, a constructor has the same name as that of the class and does not have
any return type. For example,

class Test {
Test() {
// constructor body
}
}

Here, Test() is a constructor. It has the same name as that of the class and doesn't have a
return type.
Example: Java Constructor
class Main {
private String name;

// constructor
Main() {
[Link]("Constructor Called:");
name = "Java\";
}

public static void main(String[] args) {

// constructor is invoked while


// creating an object of the Main class
Main obj = new Main();
[Link]("The name is program " + [Link]);
}
}

Output:
Constructor Called:
The name is program of java

In the above example, we have created a constructor named Main().


Inside the constructor, we are initializing the value of the name variable.
Notice the statement creating an object of the Main class.
Main obj = new Main();
Here, when the object is created, the Main() constructor is called. And the value of
the name variable is initialized.
Hence, the program prints the value of the name variables as Java.

Types of Constructor
In Java, constructors can be divided into three types:
1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor

1. Java No-Arg Constructors


Similar to methods, a Java constructor may or may not have any parameters
(arguments).
If a constructor does not accept any parameters, it is known as a no-argument
constructor. For example,
private Constructor() {
// body of the constructor
}
Example: Java Private No-arg Constructor
class Main {

int i;

// constructor with no parameter


private Main() {
i = 5;
[Link]("Constructor is called");
}

public static void main(String[] args) {

// calling the constructor without any parameter


Main obj = new Main();
[Link]("Value of i: " + obj.i);
}
}
Run Code
Output:
Constructor is called
Value of i: 5
In the above example, we have created a constructor Main().
Here, the constructor does not accept any parameters. Hence, it is known as a no-arg
constructor.
Notice that we have declared the constructor as private.
Once a constructor is declared private, it cannot be accessed from outside the class.
So, creating objects from outside the class is prohibited using the private constructor.
Here, we are creating the object inside the same class.
Hence, the program is able to access the constructor.

However, if we want to create objects outside the class, then we need to declare the constructor
as public.

Example: Java Public no-arg Constructors


class Company {
String name;

// public constructor
public Company() {
name = "Programiz";
}
}

class Main {
public static void main(String[] args) {

// object is created in another class


Company obj = new Company();
[Link]("Company name = " + [Link]);
}
}
Run Code
Output
Company name = Programiz

2. Java Parameterized Constructor


A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructors with parameters).
Example: Parameterized Constructor
class Main {

String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
[Link](languages + " Programming Language");
}

public static void main(String[] args) {

// call constructor by passing a single value


Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Run Code
Output
Java Programming Language
Python Programming Language
C Programming Language
In the above example, we have created a constructor named Main().
Here, the constructor takes a single parameter. Notice the expression:
Main obj1 = new Main("Java");
Here, we are passing the single value to the constructor.
Based on the argument passed, the language variable is initialized inside the constructor.

3. Java Default Constructor


If we do not create any constructor, the Java compiler automatically creates a no-arg
constructor during the execution of the program.
This constructor is called the default constructor.
Example: Default Constructor
class Main {

int a;
boolean b;

public static void main(String[] args) {

// calls default constructor


Main obj = new Main();

[Link]("Default Value:");
[Link]("a = " + obj.a);
[Link]("b = " + obj.b);
}
}
Run Code
Output
Default Value:
a=0
b = false
Here, we haven't created any constructors.
Hence, the Java compiler automatically creates the default constructor.
The default constructor initializes any uninitialized instance variables with default values.

Type Default Value

boolean false

byte 0

short 0

int 0

long 0L

char \u0000

float 0.0f

double 0.0d

object Reference null

To learn more, visit Java Data Types.


In the above program, the variables a and b are initialized with default
value 0 and false respectively.
The above program is equivalent to:
class Main {

int a;
boolean b;

Main() {
a = 0;
b = false;
}

public static void main(String[] args) {


// call the constructor
Main obj = new Main();

[Link]("Default Value:");
[Link]("a = " + obj.a);
[Link]("b = " + obj.b);
}
}
Run Code
Output
Default Value:
a=0
b = false

Important Notes on Java Constructors


 Constructors are invoked implicitly when you instantiate objects.
 The two rules for creating a constructor are:
1. The name of the constructor should be the same as the class.
2. A Java constructor must not have a return type.
 If a class doesn't have a constructor, the Java compiler automatically creates a default
constructor during run-time. The default constructor initializes instance variables with
default values. For example, the int variable will be initialized to 0
 Constructor types:
No-Arg Constructor - a constructor that does not accept any arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the Java compiler if
it is not explicitly defined.
 A constructor cannot be abstract or static or final.
 A constructor can be overloaded but can not be overridden.

Constructors Overloading in Java


Similar to Java method overloading, we can also create two or more constructors with different
parameters. This is called constructor overloading.
Example: Java Constructor Overloading
class Main {

String language;

// constructor with no parameter


Main() {
[Link] = "Java";
}

// constructor with a single parameter


Main(String language) {
[Link] = language;
}
public void getName() {
[Link]("Programming Language: " + [Link]);
}

public static void main(String[] args) {

// call constructor with no parameter


Main obj1 = new Main();

// call constructor with a single parameter


Main obj2 = new Main("Python");

[Link]();
[Link]();
}
}
Run Code
Output
Programming Language: Java
Programming Language: Python

In the above example, we have two constructors: Main() and Main(String language).
Here, both the constructors initialize the value of the variable language with different values.
Based on the parameter passed during object creation, different constructors are called, and
different values are assigned.
It is also possible to call one constructor from another constructor

You might also like