This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Number class doubt?

 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys,

Consider the code below,

Integer i1 = 5000;
Number n1 = 5000;

How does this compile and also when I tried n1.equals(i1) returns true??

Confused. I thought Number class is abstract and cannot be instantiated. Then when we say Number n1 = 5000;, what actually happens?? and of what type is that?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A variable of type Number can be assigned a reference of type Number or a subclass thereof. You are assigning 5000, What's that? It is an int literal. So using the concept of autoboxing the compiler converts the int to an Integer wrapper object which is a subclass of Number. Cool, what?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To explain about the equals being true, think about what you have already learned about polymorphism and overriding.
 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Barry, thanks for the post and how does the above situation behaves in a java 1.4 compiler where there is no auto boxing?
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jothi Shankar Kumar Sankararaj posted December 10, 2006 05:30 AM
Barry, thanks for the post and how does the above situation behaves in a java 1.4 compiler where there is no auto boxing?

When you have the jdk 1.5 you can also make it compile the old fashioned way:
javac -source 1.4 YourFile.java

Just try it!


Yours,
Bu.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic