GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Arrays and objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Arrays and objects" Watch "Arrays and objects" New topic
Author

Arrays and objects

Laura Arnold
Greenhorn

Joined: Nov 24, 2000
Posts: 3
How do I create an array of objects?
For example I have a class that makes a rectangle. I am using another applet class to draw the rectanfgle to the screen. I'm trying to create an array of rectangle objects to make multiple rectangles on the screen. Thanks for your help.
Allen Alchian
Ranch Hand

Joined: Oct 11, 2000
Posts: 83
The following would create an array, called polygons, of six references to objects of type Rectangle...
//create references to Rectangle objects
Rectangle rec1, rec2, rec3, ...
// create your array, called polygons
Rectangle polygons[] = new Rectangle[6];
// now assign rectangle objects to
// each array element...
polygons[1] = new rec1;
polygons[2] = new rec2;
...

[This message has been edited by Allen Alchian (edited November 25, 2000).]
[This message has been edited by Allen Alchian (edited November 25, 2000).]


Allen
Laura Arnold
Greenhorn

Joined: Nov 24, 2000
Posts: 3
Thanks for your help. When I try to do this, I keep getting a syntax error saying that another [] is expected in the line:
polygons[1] = new rect1;
Kalidas Pavi
Ranch Hand

Joined: Nov 20, 2000
Posts: 42
Laura,
try this
// initialize the rectangle objects after creating array and // rectangle objects as mentioned by Allen
rec1 = new Rectangle ( 20,30,40,50);
rec2 = new Rectangle ( 40,40,40,50);
.....
// assign the rectangle objects to the array elements.
// here the new is not required.
polygons[1] = rec1;
polygons[2] = rec2;
Hope this helps (and compiles properly!).
Kalidas.
Allen Alchian
Ranch Hand

Joined: Oct 11, 2000
Posts: 83
Thanks Kalidas.
Laura Arnold
Greenhorn

Joined: Nov 24, 2000
Posts: 3
Thank you both for all your help!
 
GeeCON Prague 2014
 
subject: Arrays and objects