I was going through Mock
test where I came across this question:
Que. What will be the result of compiling and running the given program?
Select one correct answer.
<PRE>
1 class sample
2 {
3 sample(
String s)
4 {
5 System.out.println("String");
6 }
7 sample(Object o)
8 {
9 System.out.println("Object");
10 }
11 }
12 class constructor
13 {
14 public static void main(String arg[])
15 {
16 sample s1=new sample(null);
17 }
18 }
</PRE>
a. Compile time error as call to constructor at line no. 16 is ambigious.
b. Run time error as call to constructor at line no. 16 is ambigious.
c. Program compiles correctly and prints "object" when executed.
d. Program compiles correctly and prints "string" when executed.
Ans: is 'd'
Explanation:Whenever a method/Constructor has an argument which matches two different methods/Constructors definations then it will always call the most specific one.As in our case Object is a general class and is super class of all other classes so it will call the String version of the Constructor.
I modified the above program and run:
<pre>
class sample
{
sample(MyClass s)
{
System.out.println("MyClass");
}
sample(Object o)
{
System.out.println("Object");
}
/*sample ( MyAnotherClass i)
{
System.out.println( "MyAnotherClass" );
}
*/
}
class MyClass {
MyClass(){
}
}
/*
class MyAnotherClass {
MyAnotherClass(){
}
}
*/
class constructor
{
public static void main(String arg[])
{
sample s1=new sample(null);
}
}
</pre>
I get o/p: MyClass
when I removed the comment and then run then I got:
Construtor is ambiguous.
I again modified and then try to run same program:
<pre>
class sample
{
sample(MyClass s)
{
System.out.println("MyClass o1");
}
sample(Object o)
{
System.out.println("Object");
}
sample ( MySubClass i)
{
System.out.println( "MySubClass" );
}
}
class MyClass {
MyClass(){
}
}
class MySubClass extends MyClass{
MySubClass(){
}
}
class constructor
{
public static void main(String arg[])
{
sample s1=new sample(null);
}
}
</pre>
I get the o/p: MySubClass
can anyone explain me..
how the null is treated when it is used instead of any object reference ------------------
Regards
Ravish