Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor call

 
sreenivas kup
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic