Mar 28, 2008

Some java fun !

What will be the output of this simple program?

pretty simple, isn't it? :)


public class A
{

public void f(Exception e)
{
System.out.println("A");
}

public static void main(String args[])
{
A a = new B();
a.f(new RuntimeException());
}


static class B extends A {

public void f(RuntimeException e)
{
System.out.println("B");
}

}
}

3 comments:

Wanderlust said...

The answer is:
A
A

for those of you who don't know why - in case of method overloading, the method call is made by reference and not the actual instance :)

Matka/HTML said...

Uncle your answer is correct (A) but the logic doesn't seem right. Method calls are still made for the actual instance, this behavior is because B inherited the method from A and didn't override it. So A's implementation was called. Try this example and you would see what i'm talking about. Its possible to get confused about the method parameters, but even if one of them is just subclass of the other, they will be considered two different methods overloaded with different parameters.

public class A
{

public void f(Exception e)
{
System.out.println("A");
}

public static void main(String args[])
{
A a = new B();
a.f(new Exception());
}


static class B extends A {
public void f(Exception e)
{
System.out.println("BA");
}
public void f(RuntimeException e)
{
System.out.println("B");
}

}
}

Wanderlust said...

Sorry uncle.. now check the post again..i put in the wrong code.. i have edited it now...i intended it to be.. a.f(new RuntimeException) :)

and we both are at the same point when talking about overloading... now what i had originally asked falls into context.. class B has two methods now.. f(Exception) and f(RuntimeException).. but now if you do A a= new B() and a.f(RuntimeException).. class A's method will be executed.. and the answer will be A.. try this out yourself.. :) so my point was that in case of overloading, first the reference type will be checked (in this case class A) if that reference type has a method which can be called (f.(RuntimeException) can be called on A's f.(Exceptin)), then that particular method of the refernce will be called...

and what u said abt overloading is correct..i put the wrong code that is why u thot my explanation ws wrong.. run this new code now...