What is Method Overloading in java

Posted By on October 2, 2014


Download PDF
Short Circuited Operators in JAVA
Difference between constructor and method

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 are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading.

Method overloading is one of the ways that Java supports polymorphism.

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. Thus, overloaded methods must differ in the type and/or number of their parameters.

While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.

 

Example::

class RectDemo
{
int volume()   // method without argument
{
int vol = 0;
return vol;
}

int volume(int length)   // method with one argument
{
int vol = length * length;
return vol;
}
int volume(int length, int breadth)     // method with two argument
{
int vol = length * breadth;
return vol;
}
}

class Rectangle
{
public static void main(String a[])
{
RectDemo r1 = new RectDemo();   // Creating an object….
int vol;     // used to store volume
vol = r1.volume();   // volume method without argument is called
System.out.println(“Volume of r1 is : “+vol);

vol = r1.volume(10);   // volume method with one argument is called
System.out.println(“Now, Volume of r1 is : “+vol);
vol = r1.volume(10,20);     // volume method with two argument is called
System.out.println(“Now, Volume of r1 is : “+vol);
}
}

 

This program generates the following output::
Volume of r1 is : 0
Now, Volume of r1 is : 100
Now, Volume of r1 is : 200

 

 

Short Circuited Operators in JAVA
Difference between constructor and method

Download PDF

Posted by Akash Kurup

Founder and C.E.O, World4Engineers Educationist and Entrepreneur by passion. Orator and blogger by hobby

Website: http://world4engineers.com