Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor..

 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ankit, i tried some programs on it and now i am clear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic