• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question about overloading (OCPJP) Boyarsky & Selikoff  RSS feed

 
Helene Shaikh
Greenhorn
Posts: 21
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a question on page 4. It says that when overloading methods, Java will first look at a matching superclass type, and then later to an autoboxed type. However, in my example, it's the other way around. It prints the autoboxed type instead of the superclass type.

 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does int type inherit from Number? Nope. 'int' is a primitive data type, which is different from usual Class type. Look which classes actually inherit from Number. If method with Integer signature wouldn't be there, then behind the scenes I believe int would be wrapped to Integer and only then method signature with Number would be invoked.
 
Helene Shaikh
Greenhorn
Posts: 21
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Integer does inherit from Number:

According to the documentation "The direct subclasses of Number are AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, DoubleAccumulator, DoubleAdder, Float, Integer, Long, LongAccumulator, LongAdder, Short"
 
Helene Shaikh
Greenhorn
Posts: 21
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay thanks for the answer!
 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's right. So, but not an int. int and Integer aren't the same. When you pass 3, you pass an 'int'. So, it gets autoboxed and method with Integer signature is being used. If you were to remove method with signature Integer, then still 3 would get autoboxed to an Integer, and then would happen what you read in the book, it would use its superclass signature Number, which Integer extends.
 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this topic you'll find 15 small code snippets to test your knowledge about method overloading
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!