aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Arrays Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Arrays Doubt" Watch "Arrays Doubt" New topic
Author

Arrays Doubt

aslika bahini
Ranch Hand

Joined: Mar 03, 2007
Posts: 111
Hi There,

I have a doubt in the following code.
In the line #1 animal[0]= new Cat(); throws an ArraysStoreException.
Can any of you please explain?




Thanks in Advance
Saritha
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9280
    
  17

That's because Dog and Cat are siblings. You cannot add an instance of Cat into an array of Dogs.

Now you will say that the array is of Animals. But actually only the reference is an Animal array. Actually the array itself is a Dog array. Consider this code

Dog dogArr = new Dog[5];
Animal[] arr = dogArr;
arr[0]=new Cat();//ArrayStoreException
Dog dog = godArr[0];//1

Now if there was no ArrayStoreException at the line indicated, then there would be a abnormal situation at line 1. So an array can only store objects of the actual array type. You can read my blog for a detailed article. The link is in my signature...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
chander shivdasani
Ranch Hand

Joined: Oct 09, 2007
Posts: 206

It is a Classic example to why Generics came into existence


Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
Mohammad Khan
Ranch Hand

Joined: Sep 23, 2008
Posts: 37
// Following code might help to understand the issue


abstract class Animal {}

class Dog extends Animal {}

class Cat extends Animal {}

class Cow extends Animal {}

public class MyApp {

public static void main(String[] args) {
Animal[] animals = { new Dog(), new Cat(), new Cow() };
Dog[] dogs = { new Dog(), new Dog(), new Dog(), new Dog() };

MyApp app = new MyApp();

try {
app.doStuff(animals);
app.doStuff(dogs);
} catch (AnimalException e) {
System.out.println("Raised exception while trying to store NOT-A Dog in Dog[]");
}
}

public void doStuff(Animal[] animals) throws AnimalException {
if (animals instanceof Dog[]) {
animals[0] = new Dog();
} else {
throw new AnimalException();
}
}
}

class AnimalException extends Exception {}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Arrays Doubt
 
Similar Threads
ArrayStoreException pls explain?
a question about polymorphism ??
Help me fix this-Part-2,so I can compile(generics doubt)
doubt in polymorphism
Help me fix this,so I can compile(generics doubt)