• Post Reply Bookmark Topic Watch Topic
  • New Topic

create a java object using factory methods  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I want to create a java object with out using new key word,
Please do help thanks in advance.
 
Ranch Hand
Posts: 172
Java MySQL Database Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.


The new operator is used 99% of the times to create a java object but there are other ways to do it too like
1) Using Class.forName() If we know the name of the class & if it has a public default constructor we can create an object;
Class.forName actually loads the class in Java but doesn’t create any Object. To Create an Object of the Class you have to use newInstance method of Class class.
2) Using clone() The clone() can be used to create a copy of an existing object.
3) Using object deserialization Object deserialization is nothing but creating an object from its serialized form.
4) We can also use Class Loader to create Object of a Class. This way is some what same as Class.forName option.

Hope this helps
 
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mayuri,
Welcome to CodeRanch!

There are two ways of answering your question. One is literally - which is what Ashish did. The other is using the information in the subject about factory methods. With a factory method, "new" is in fact called. It's just called by the factory class and not your code. So your code looks like: factory.newObject(). The "new" call is hidden inside the "newObject" method.
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mayu shines wrote:I want to create a java object with out using new key word,


Why?

Is this an academic exercise, and you're trying to discover what all the possible ways of creating an object are?

Or are writing a program and you've hit a point where you can't use new for some reason? If so, what is that reason?

The more context you provide, the better the answer we can give.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!