File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Beginner / Object Creation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Beginner / Object Creation" Watch "Beginner / Object Creation" New topic

Beginner / Object Creation

ed jones

Joined: Oct 01, 2008
Posts: 11

my goal is to create say 100, small fillable rectangles

if I put, inside a "for" loop

GRect myRect = new GRect( .........etc

I can create the rectangles

my question is,is this correct, ie: should each rectangle be a "new" GRect, or is there a way to just make copies of the first GRect?

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46352
Yes, you can create 100 Rectangles by saying new inside a for loop.
Copying is likely to be more complicated than simply writing new.

There is a problem here, however; you are declaring and creating the Rectangle in the same statement inside the loop. Unless you have a reference to attach the Rectangle to (eg a Rectangle[]), in which case the declaration is unnecessary, your Rectangles will go out of scope at the end of the loop and vanish into cyber-limbo never to be seen again!

Another thing lots of people try (instead of copying) is something like this rect2 = rect1;. Try it and see what happens to rect2 when you fill rect1.
Don Solomon
Ranch Hand

Joined: Jul 20, 2008
Posts: 48
check-out the flyweight pattern. just depends on what you are doing with the objects.

Software development is an exercise in thinking not coding.
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3152

my question is,is this correct, ie: should each rectangle be a "new" GRect, or is there a way to just make copies of the first GRect?

Creating a copy of the object is slightly complicated where in one has to override the clone method and use it for creating a copy. Actually there are two versions: One is to use another reference variable to point to the object created in which case its not copying and the other version is a new reference variable pointing to the clone object.

In your loop as and when you create Rectangle objects they are eligible for garbage collection after the end of the each iteration because there is no reference to access the object as the same reference will now be pointing to the new object on the heap.

Mohamed Sanaulla | My Blog
I agree. Here's the link:
subject: Beginner / Object Creation
jQuery in Action, 3rd edition