• Post Reply Bookmark Topic Watch Topic
  • New Topic

Meaning of Null passed for an object reference  RSS feed

shyama chandra
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When the following piece of code is run, the following is the output.
Test(String) executed

If the method m1 is overloaded to take the class D, a compilation error
"reference to m1 is ambiguous, both method m1(D) in Test and method m1(B) in Test match" is obtained. (commented here)

How is "null" resolved to the last child of the hierarchy. Is this done during compilation time? How to understand this behavior?

public class Test
public Test(Object ref){System.out.println ("Test(Object) executed");}
public Test(String ref){System.out.println ("Test(String) executed");}
public Test(){System.out.println ("No argument constructor execute");}

public void m1(A a)
{System.out.println ("A");}
public void m1(B b)
{System.out.println ("B"); }
public void m1(Object o)
{System.out.println ("O"); }
/*public void m1(D d){System.out.println ("D");}*/

public static void main(String[] args) {
Test ps = new Test(null);

class A{}
class B extends A{}
class D{}
Ernest Friedman-Hill
author and iconoclast
Posts: 24217
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Welcome to JavaRanch!

When you signed up for the Ranch, you may have been in a hurry, and therefore didn't take the time to read about our policy on names. You're going to need to do that now. Your display name has to be a real first and last name, no "java" or "hax0r" or such like. You can change your display name here. Please do it, pronto. Thanks, pardner!

Now, on to your question: overloaded methods like these are indeed resolved at compile time. The rule is pretty simple: for any given call, the "most specific" interpretation will be chosen. So if you've got two versions of a method "m1" that accept String and Object respectively, because String is derived from Object, then m1(null) will be interpreted as m1(String), because although both versions could possibly apply, the String version is more specific -- i.e., more derived.

In your later version, the A/B/Object set is unambiguous because B is derived from A, and A from Object; m1(null) is then m1(B), because B is the most specific. But A/B/D/Object is ambiguous, because B is the most derived class in one inheritance tree, and D in another tree (the "depth" of the tree doesn't matter) and the compiler has no way to choose between these two trees.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!