| Author |
Confusion regarding object creation in Java.
|
Rahul Ba
Ranch Hand
Joined: Oct 01, 2008
Posts: 203
|
|
I know there are two ways to create an object in java. They are as below
First way is by setter
1)
other way is by constructor
2)
It is prefered to use second option while creation of the object. I agree with this, because first step involves two step approach while creatinn an object.
My question here is when to use POJO or javabean..as like in the first step....is there any circumstance of using it?
Thanks in advance.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32611
|
|
The set methods do not create a new object. They modify an existing object. In the example you gave, only calling a constructor creates a new object.
Creating an object in Beans calls a no-argument constructor to create the object. Its attributes are altered with the setXXX methods.
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 3026
|
|
Rahul Ba wrote:
I know there are two ways to create an object in java. They are as below
There is really only one way of generating Objects in Java - and that is with the new operator. (with some exceptions for Strings and autoboxing).
Rahul Ba wrote:
First way is by setter
1)
other way is by constructor
2)
It is prefered to use second option while creation of the object. I agree with this, because first step involves two step approach while creatinn an object.
My question here is when to use POJO or javabean..as like in the first step....is there any circumstance of using it?
Thanks in advance.
I guess you mean there are two ways to assign data to new objects, either through setXXX() methods or by passing the value into the constructor.
The biggest difference between the two methods is what is allowed to happen to the data, once the object is created. If the value is allowed to change, then you should make a setXXXX() method to change the value. If the value is not allowed to change after Object creation then pass the value in to the constructor and don't have a setXXXX() method.
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56162
|
|
|
Or, as previously pointed out, in the cases where the class must have a nullary constructor.
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
 |
|
|
subject: Confusion regarding object creation in Java.
|
|
|