It doesn't allow this because the Java designers (correctly) recognized that the boolean / integer overloading in C and C++ was a significant source of errors.
(I recall seeing that in writing in some design rationale, but I can't find it.)
For instance:
if (i = 0) { ... }
is legal but probably a bug in C or C++.
Java avoid this and other problems by making boolean
and the integer datatypes different types that cannot be converted from one to the other. Thus, the above is a compilation error in Java.
Now this doesn't explain why you cannot explicitly type cast a boolean
to an int
. But I think that can be understood by observing the following:
You rarely need to do that in real Java programs.
Number <-> boolean casting wouldn't jell with the way that other type casts work. In particular, for other types there are up-casts and down-casts, and up-casts in Java don't require an explicit type cast.
You can't typecast between numbers and string either, or between strings an other objects. These are conversion, not type casts. And
in <-> boolean
is too.
Read full article from types - Why Doesn't Java Allow Casting Boolean -> Int? - Stack Overflow
No comments:
Post a Comment