views:

86

answers:

5

I create an object of the class

Rectangle rec = new Rectangle(2,4);

Which gives my rectangle and height of 2 and a width of 4.

But is there anyway I can call the no arg constructor later on in my code without creating a new object?

without doing this:

Rectangle rec2 = new Rectangle();

+2  A: 

Normally this is a sign that you need to refactor your constructors such that all the code which is common to two or more constructors is contained within a separate (non-constructor) method.

Paul R
A: 

no you cannot. You can use reflection for creating a new object without using new keyword, but i am not sure whether it calls a constructor.

GK
+1  A: 

Constructors by their definition create new objects.

If you no longer need rec you can do rec = new Rectangle() provided the Rectangle has no no arg constructor.

Or you just want to replace the values of the current rectangle? if so just change via setters for create a method to update both values...

HadleyHope
rec = new Rectangle() called the no arg contstructor in the object I already created. Thanks!
vhflat
No it didn't. it created a new rectangle and assigned your variable holding your old rectangle to the new rectangle.
Sam Holder
A: 

You can set the basic properties of your Object in a method and call that method in constructors

or

In your case use rec = null; rec = new Rectangle();// if you don't require Rectangle(2,4)

Ravia
A: 

No, you can only call one constructor.

If you want to overwrite the coordinates you can use the setBounds method, e.g.

rec.setBounds(0,0,0,0);

But unless you're developing a mobile phone game, there's not much point in re-using the old rectangle, and it's simpler to create a new one.

finnw