aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructor call Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructor call" Watch "Constructor call" New topic
Author

Constructor call

sreenivas kup
Greenhorn

Joined: Sep 10, 2004
Posts: 7
Hi folks,

Plz look at the below code.


Case 1:
---------------------------------------------
class A {

A(Object o) {System.out.println("o");}

A(String s) {System.out.println("s");}

public static void main(String args[]) {
new A(null);
}


}
------------------------------------

The output is: s...


Case 2:

-----------------------------------------------------
class B {

B (C c) {System.out.println("c...");}

B (Object o) {System.out.println("o...");}

B (String s) {System.out.println("s...");}


public static void main(String args[]) {
new B(null) {};
}


}

class C {}
------------------------------------------------------
The compiler is not happy and displaying the below error messages

B.java:12: reference to B is ambiguous, both method B(C) in B and method B(java.lang.String) in B match
new B(null) {};
^
B.java:12: cannot resolve symbol
symbol : constructor B ()
location: class B
new B(null) {};
^
2 errors



1) Why is the Subclass constructor being called in Case 1?

2) Why is the code in case 2 failing to compile?

Plz explain me. May be I am missing basics here

Thx,
Sreenivas
Vipin Das
Ranch Hand

Joined: Jul 05, 2004
Posts: 47
Hi sreenivas,
If there are overloaded methods(here the constructor is overloaded), always the methods with more specific parameters is used to resolve the ambiguity. In our case we have 2 constructors one with object and the other with string. Here a null value is applicable to both Object and String. Since string is the subclass, it is a more specific implementation therefore it will be called. But in case 2 there are 2
methods, both are subclasses of object, so the compiler cannot identify the method to call. That is the problem.
-vipin
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Constructor call