Hey Arshu,
Regarding your query now I'm going to explain about the Method Overloading (or Function Overloading ) concept in Java.
Basically system finds the best match of the function arguments and the parameter list (i.e types and numbers or parameters) during program compilation. This phenomenon is termed as static building.
Hence function overloading is the process of defining functions/ methods with the same function names but with different numbers and types of parameters.
Reason for using it :
An object contains State and Behaviour ( Data and Functions). Sometimes it's intended to perform similar operations with a slight change in the parameters.
A number or methods are used to implement a single interface in Java i.e. polymorphism. If different function names are used for similar operations then users may have a lot of interactions and they require to remember a number of function names at the time of invocations.
Hence it's reliable to use many functions with the same namea forr similar operations.
Let's discuss the whole thing practically with a short and simple program :
Q: Write a class with the name 'volume' . Using function overloading compute the volume of a cube, a sphere and a cuboid in Java :
Answer:
import java.util.*;
class volume
{
void vl(int s)
int v;
v=s*s*s;
System.out.println("volume of cube:"+v);
}
void vl(double r)
double v;
v=1.33*3.14*r*r*r;
System.out.println("volume of sphere:"+v);
void vl(int l,int b,int h)
v=l*b*h;
System.out.println("volume of cuboid:"+v);
public static void main(String args[])
Scanner sc=new Scanner( System.in (http://System.in) );
volume obj= new volume();
int s;
double r;
int l,b,h;
System.out.println("enter the side for cube:");
s= sc.nextInt();
System.out.println("enter the radius for sphere:");
r= sc.nextDouble();
System.out.println("enter the length for cuboid:");
l= sc.nextInt();
System.out.println("enter the bredth for cuboid:");
b= sc.nextInt();
System.out.println("enter the height for cuboid:");
h= sc.nextInt();
obj.vl(s);
obj.vl(r);
obj.vl(l,b,h);
Just go through and analyse the above code minutely . Here I'm performing the similar operation in each case ( i.e. calculating the volume) with just one class named "volume". Hence this is the method overloading .
I think now the whole thing becomes clear to you. If you've any query regarding this just ask in the comment section, I'll definitely explain.
Thank you.
Regular exam updates, QnA, Predictors, College Applications & E-books now on your Mobile