| Author |
constructor..
|
Preethi Dev
Ranch Hand
Joined: Sep 07, 2008
Posts: 265
|
|
hi i got it from http://www.go4java.20m.com/mock1.htm class AA{} class BB extends AA{} class sample { sample(BB b) { System.out.println("String"); } sample(AA a) { System.out.println("Object"); } } class constructor { public static void main(String arg[]) { sample s1=new sample(null); } } i thought the answer would be compile error because of already defined constructor, but i am getting "String". can anyone explain me why so? thanks in advance
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
Originally posted by Preetha Arun: i thought the answer would be compile error because of already defined constructor, but i am getting "String".
I didn't understand what you meant by this but you get String as output because when you pass null, and more than one matching methods or constructors take a reference as a parameter, than the compiler chooses the one lower in the inheritance hierarchy. Since BB is lower in the hierarchy than AA, so constructor with BB as parameter is chosen. Remember that this rule applies to only classes in the same hierarchy. If two methods take String and Integer as parameter and you pass null, then there will be a compile time error saying ambiguity. This works only with classes which have super-class and sub-class relationship...
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
Preethi Dev
Ranch Hand
Joined: Sep 07, 2008
Posts: 265
|
|
|
Thanks Ankit, i tried some programs on it and now i am clear.
|
 |
 |
|
|
subject: constructor..
|
|
|