This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is ArrayStoreException and when it happens

 
faisal usmani
Ranch Hand
Posts: 139
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 64
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 139
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx Harshil

I got u
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic