this & overloading methods
this & overloading methods
It is illegal in Java to declare two local variables with the same name inside the same method or a
constructor. But we can have local variables, including formal parameters to methods, which overlap
with the names of the class ’ instance ‘ variables. However, when a local variable has the same name
as an instance variable, the local variable hides the instance variable. This is why width, height, and
depth were not used as the names of the parameters to the Box( ) constructor inside the Box class. If
they had been, then width would have referred to the formal parameter, hiding the instance variable
width.
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the
this keyword. this can be used inside any method to refer to the current object. That is, this is always
a reference to the object on which the method was invoked. ‘this’ lets you refer directly to the object,
you can use it to resolve any name space collisions that might occur between instance variables and
local variables.
this.width = width;
this.height = height;
this.depth = depth;
}
Method Overloading
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 implements 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.
The main objective of method overloading is to ‘Generalize a method’ to reduce complexity. When
we use many method names for similar functions , it will increase the complexity of Application.
class OverloadDemo
void display()
System.out.println("No parameters");
return a*a;
}
class Overload
double result;
ob. display();
ob. display(10);
No parameters
a: 10
a and b: 10 20
double a: 123.25
Here, display( ) is overloaded four times. The first version takes no parameters, the second takes one
integer parameter, the third takes two integer parameters, and the fourth takes one double
parameter. The fact that the fourth version of display( ) also returns a value is of no consequence
relative to overloading, since return types do not play a role in overload resolution. When an
overloaded method is called, Java looks for a match between the arguments used to call the method
and the method’s parameters.