File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes What is ArrayStoreException and when it happens Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What is ArrayStoreException and when it happens" Watch "What is ArrayStoreException and when it happens" New topic
Author

What is ArrayStoreException and when it happens

faisal usmani
Ranch Hand

Joined: Jan 14, 2006
Posts: 139
Hi ranchers ,

I have this small problem of 'ArrayStoreException' ,please help me , here is my code


++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class Base
{

public void show()
{
System.out.println("Inside Base show");
}

}




class Derived extends Base
{

public void show()
{
System.out.println("Inside Derived show");
}

public void display()
{
System.out.println("Inside Derived display");
}

}
class Demo
{
public static void main(String a[])
{
Derived dr[] = new Derived[10];
Base br[];
br = dr ;
br[0] = new Base(); // Exception is thrown on this line
br[0].show();
}
}


There is no compile time error but when i try to run , it gives me an 'ArrayStoreException' , as per my book "All arrays remember the element type with which they are created and they monitor that only compatible references stored in it" . Here br is compatible to Base class then why does
it throw exception on doing ( br[0] = new Base(); )

Can anybody just explain me with respect to this code "Please"


Thanx in advance

regards
Harshil Mehta
Ranch Hand

Joined: Mar 17, 2005
Posts: 64
hello faisal,

as per my book "All arrays remember the element type with which they are created and they monitor that only compatible references stored in it".


your book is 100% correct.

Here br is compatible to Base class then why does
it throw exception on doing ( br[0] = new Base();


[bold]br is compatible with Base class, not the references of the objects in the array referred by br are compatible with Base class.[/bold]
here br is referring to an array whose elements are declared to be of type Derived. So you can assign br[0] to either Derived object or object of any subclass of Derived, [bold] but not to supertype of Derived[/bold].

hope this helps you.
faisal usmani
Ranch Hand

Joined: Jan 14, 2006
Posts: 139
Thanx Harshil

I got u
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: What is ArrayStoreException and when it happens
 
Similar Threads
Assigning subclass obj to superclass ref
Reference casting question
ArrayStoreException
confusion in the output
Super and subclass