aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes constructor.. 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.." Watch "constructor.." New topic
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
Sheriff

Joined: Aug 03, 2008
Posts: 9313
    
  17

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: constructor..