• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Implicit promotion for constructor arguments

 
Andreas Sandberg
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,

Can somebody explain why the code below compiles. Why does Main a = new Main(3) call the constructor that takes the float argument. How does JAVA handle implicit promotion for constructor arguments? Thanks!

 
Seb Mathe
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's because an int can be automaticly converted to a float (or to a long, or a double)
 
Raghu Shree
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

int value 3 is converted into float. So Math(3) is executed. For more information about casting refer this link.

http://www.javaranch.com/maha/Resources/CarlsNotes.txt
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

You can look at this way


byte->short->int->long->float->double

In fact here you can have char converts into int...apart from short...

char->int..



[ October 20, 2005: Message edited by: A Kumar ]

[ October 20, 2005: Message edited by: A Kumar ]
[ October 20, 2005: Message edited by: A Kumar ]
 
Henry Wong
author
Marshal
Pie
Posts: 21490
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try it with code tags...

Henry

 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.

Thanks Henry...Thats what i was trying to convey...


 
Thomas Drew
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andreas
In your constructor Main(float i) you pass the float value for i in but you never assign it to anything. The this() call your constructor with no arguments which is always going to assign the value 3 to i.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic