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 array initialization problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "array initialization problem" Watch "array initialization problem" New topic
Author

array initialization problem

sandeep patrudu
Greenhorn

Joined: Feb 22, 2007
Posts: 6
Hi everyone,

What was the problem with code given below





class A { }
class B extends A { }
class C extends B { }


class l {




public static void main ( String args [ ] ) {
A [ ] x = new B [ 3 ] ;
x [ 0 ] = new A ( ) ; // ---> line 1
x [ 1 ] = new B ( ) ; // ---> line 2
x [ 2 ] = new C ( ) ; // ---> line 3
}

}


it is compiling but throwing exception at runtime.



Thanks,
sandeep
pete stein
Bartender

Joined: Feb 23, 2007
Posts: 1561
Though x was initially declared an array of A, it is initialized as an array of B. You can't store an "A" object in a "B" variable though you can store sub classes there such as C.
sandeep patrudu
Greenhorn

Joined: Feb 22, 2007
Posts: 6
Hi Pete,
Thanks for helping on this.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: array initialization problem
 
Similar Threads
Explain ...
casting
Pelase Help me out imme....
why does it do not show an compile time erroe at line 3?
Exception whith Cast ...it's strange