Java - Overloading Methods PDF
Java - Overloading Methods PDF
B.Bhuvaneswaran
Assistant Professor (SS)
Department of Computer Science & Engineering
Rajalakshmi Engineering College
Thandalam
Chennai 602 105
[email protected]
Overloading Methods
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.
Program
Output
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Program
Output
No parameters
a and b: 10 20
Inside test(double) a: 88
Inside test(double) a: 123.2
Overloading Constructors
In addition to overloading normal
methods, you can also overload
constructor methods.
In fact, for most real-world classes that
you create, overloaded constructors will
be the norm, not the exception.
Example
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;
}
Program
Output
Volume of mybox1 is 3000.0
Volume of mybox2 is 1.0
Volume of mycube is 343.0
Program
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
Output
ob1 == ob2: true
ob1 == ob3: false
Program
References