K
Knute Johnson
Patricia said:pek wrote:
...At that time, I tested his suggestion and replied:
Interestingly, you cannot pass null when a method requires an
enumeration!
In which he replied:
Sure you can!
[snip]
method((X)null);
[snip]
I swear that when I first tested new Card(Rank.JOKER, null) eclipse
displayed a compile-time error. I can't remember what was the error,
but now I can't reproduce it! Now new Card(Rank.JOKER, null) doesn't
yell anything! Assuming Knute also had seen this error (since he
provided a solution instead of calling me names), what's happening? ...
So what's the big deal? Is it, or is it not a compile-time error when
passing null in a method that expects an Enum?
It is not an error to pass null to a method that expects an enum.
The key is the following sentence "The direct supertypes of the null
type are all reference types other than the null type itself." in the
JLS, 4.10.2 Subtyping among Class and Interface Types at
http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.10.2
According to 8.1 Class Declaration at
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.1,
an enum declaration specifies a new named reference type. Thus each enum
type is a supertype of the null type.
As a result, conversion from the null type to any enum type is a
widening reference conversion, which is a permitted form of method
invocation conversion. 8.9 Enums,
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9,
contains various restrictions on enums, but none that prevents method
invocation conversion of null to an enum type. Indeed, a coding example
in that section contains:
private Card(Rank rank, Suit suit) {
if (rank == null || suit == null)
throw new NullPointerException(rank + ", " + suit);
this.rank = rank;
this.suit = suit;
}
which would make no sense at all if null were not method invocation
conversion to Rank and Suit, which are both enum types.
There could have been some other problem in your original test. If you
had prepared and posted an example at the time it could have been
analyzed.
Patricia
When I originally responded to pek's post I suggested casting the null
to the appropriate type because I had run into this somewhere before.
It think it occurred when I passed null to a JDialog constructor and got
a compiler warning. So when he asked his question that just came to
mind. I wonder if there was a compiler bug at some point or if I just
have an advanced case of CRS.
You know what I'll bet I know what my original problem was, the JDialog
constructor takes either a Frame, a Dialog or a Window as owner. The
compiler wouldn't know which without the cast. But maybe that is a bug,
I don't know.