• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance of a class

 
suavedeep kaur
Ranch Hand
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can we create instance of a class without using "new " in java???
 
Maneesh Godbole
Saloon Keeper
Posts: 10976
11
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Gurjit Sandhu
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10976
11
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic