wood burning stoves*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Beginner / Object Creation" Watch "Beginner / Object Creation" New topic
Author

Beginner / Object Creation

ed jones
Greenhorn

Joined: Oct 01, 2008
Posts: 11
Hello,

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?

thanks
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
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: 3071
    
  33

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: http://aspose.com/file-tools
 
subject: Beginner / Object Creation