aspose file tools*
The moose likes Beginning Java and the fly likes Instance of a class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Instance of a class" Watch "Instance of a class" New topic
Author

Instance of a class

suavedeep kaur
Ranch Hand

Joined: Jun 02, 2008
Posts: 36
can we create instance of a class without using "new " in java???



Suavedeep kaur
SCJP
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10535
    
    9

Sure!
Check out Class#forName() and Class#newInstance().
Also google around for "Singleton pattern" which enables you to obtain an object instance without your code calling new.


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Gurjit Sandhu
Greenhorn

Joined: Jan 29, 2009
Posts: 11
Hi,

You can also use clone() method on an object to create a new instance which is similar to the object on which it is being called.
However, note that clone() method does not call the constructor of the class to be invoked at the time of creating the new instance,as it just copies the object to create a new one which is exactly similar to it.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10535
    
    9

Please note the clone() belongs to the Object class and has protected modifier. So you cannot call clone on just any object reference.
Also, if the class does not implement Clonable, you end up with a CloneNotSupportedException
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
This question comes up regularly. These answers come up regularly too!

You can create a String object by writing "String".
You can create a Number object by boxing: Integer i = 3;
You can create an array object with an initialiser: int[] numbers = {1, 2, 3, 4};
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Instance of a class