Originally posted by Vejaykrishna:
HI,
In K&B book p:112 there is an example program which explains reference variable casting. can anybody explain me line: 3 and 4.
1. class CastTest2{
2. public static void main(String [] ar){
3. Animal[] a={new Animal(), new Dog(), new Animal()};
4. for(Animal animal : a){
5. animal.makeNoise();
6. if(animal instanceof Dog){
7. animal.playDead();
8. }}}}
Line 3: just creates an array of objects, all of which can be casted to an Animal object (since the array is of type Animal). The new Dog() object is a subclass of Animal and hence, can be upcasted to an Animal object and the other two elements are Animal objects.
Line 4: an example of the new enhanced for-loop in 1.5. It is initializing an object named animal which is of type Animal which will be assigned to each of the elements in the array created in line 3.
In the first iteration it animal will point to the first element in the a array (the new Animal object); in the second iteration, a will point to the second element in the array (the new Dog object). In the final iteration, it will be assigned to the second new Animal object created on line 3.
Does this answer your question?