aspose file tools*
The moose likes Beginning Java and the fly likes Confusion regarding object creation in Java. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Confusion regarding object creation in Java." Watch "Confusion regarding object creation in Java." New topic
Author

Confusion regarding object creation in Java.

Rahul Ba
Ranch Hand

Joined: Oct 01, 2008
Posts: 205

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: 38910
    
  23
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: 4181
    
  21

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: 61241
    
  66

Or, as previously pointed out, in the cases where the class must have a nullary constructor.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
 
 
subject: Confusion regarding object creation in Java.