Hi,
In
this post we will see the usage of Over loading ,Boxing and widening
concepts with an example.
Lets
see how the above concepts are related with an example :
Example
:-
public
class
WideningBoxing {
//Overloading
example with boxing and widening
public
void
method(Integer x, Integer y)
{
System.out.println("
in Integer ");
}
public
void
method(float
x, float
y)
{
System.out.println("in
float");
}
public
static
void
main(String[] args) {
WideningBoxing
wb=new
WideningBoxing();
wb.method(1,
2);
}
}
Explanation
:- Here we have two methods with same names,different parameter
types.
We
are calling this method from main .
Now
the question is which method will be invoked when we call
wb.method(1, 2);
The
method with Integer or method with float parameters?
JVM
will prefer to take widening than boxing here.
So
the output
will be
in
float
The
main reason behind this is widening was being implemented before
auto boxing, so the API writers thought that the existing
functionality should work same ,it should not be changed by adding
new auto boxing feature.
This
is the common Java interview Question
Note
:- Widening is preferred than Boxing
This
is the key take away point from this post.
Happy
Learning
Please
provide your valuable comments on this article and share it across
your network.
Contact
me @ sudheer@javarecent.com
or admin@java-recent.com
No comments:
Post a Comment