File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusion regarding object creation in Java.

 
Rahul Ba
Ranch Hand
Posts: 206
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Pie
Posts: 47292
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 4181
21
IntelliJ IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64192
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or, as previously pointed out, in the cases where the class must have a nullary constructor.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic