This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
There is a distinction betwee the class of an object and the type of a reference to an object. For example, a reference of type Integer can refer to an Integer object. So can a reference of type Number and a reference of type Object because these are the superclasses of Integer.
If I say "Integer I = new Integer(3);", I can then say "Integer P = I:", "Number N = I;", or "Object J = I;" without using the cast operator. This is because "I" cannot possibly refer to an object that is not also a Number and an Object.
But a Number reference could refer to a Float with "Number N = Float(2.5f);"
So "I = N" may or may not work, depending on the value of N. In this case, I have to say "I = (Integer)N;". This tells the compiler "I know what I'm doing. I'll never execute this statement unless N refers to an Integer object". If you're wrong, you'll get a ClassCastException".
Quite a few Java library methods, like the collections, return a reference of type Object and expect you to cast the object to the type you need, based on your knowledge of the actual type of the object. That way, the library code doesn't have to worry about the type of object it is handling.
[ December 09, 2004: Message edited by: Mike Gershman ] [ December 09, 2004: Message edited by: Mike Gershman ]
Originally posted by April Benzine: Integer accessCount = (Integer) session.getAttribute("accessCount");
(Integer) is casting. What is the purpose of this? Aren't you already saying that accessCount is of type Integer? When is it correct to use this?
The fact that accessCount is of type Integer is exactly the problem that the casting solves. This probably doesn't match the return type declared by the getAttribute() method. I suspect that getAttribute() is declared to return Object. If you have a reference to a superclass object, then you have to cast it in order to assign this to a subclass reference. That's probably not the best wording, so I suggest you look on the web, or better yet in a textbook, for more information about inheritence and reference types.