1. animals[i is an Object (as far as the compiler knows, because that's how you declared it), and Objects don't have a makeNoise() method. The code checks that this particular Object is in fact a Cat, the uses the cast (Cat) to tell the compiler that this particular reference to animals[i] is actually a reference to a Cat. The compiler says "ok, if you say so..) and now knows that the makeNoise() method is valid. If you get this wrong then there will be an error at runtime when it finds out that animals[i] isn't really a Cat.
2. Class D overrides foo(), so if the code on line 30 just read foo(t) that would call the same method - infinite loop. With super. it calls the version of foo defined in the superclass (B) - which prints "B", then prints "D". Not very useful, but safe.
JamesCherrill
Posting Genius
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
chaospie:
What you say is basically right, but it hides an important point that can confuse learners. You cabnnot "cast an object". An Object's class is unalterable. What you are casting is the reference. Ie you are saying "this ref to an Object is really a ref to Cat". The object iteself was, and always will be a Cat.
JamesCherrill
Posting Genius
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
Good question - the difference is because ints and doubles are primitive types, they are not accessed via a reference, and the cast creates, in effect, a new primitive and performs the conversion to initialise it. Cats and Objects are objects and are accessed by reference variables, and it's these references that are cast in that case.
So, to answer the question, the primitibve and the Object cases are quite different.
JamesCherrill
Posting Genius
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
Not sure what point you are trying to make here tong1, but the bald statement "Therefore neither casting nor the instanceof operator is needed" could easily mislead a learner.
toString is a special case because it's one of the very few methods defined for Object, and therefore inherited by every object in Java. Because, and only because, its defined in Object, you don't need to cast.
In the case shown by the O/P the instanceof and cast are necessary, as they are for all but the very few methods defined in Object.
JamesCherrill
Posting Genius
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073