File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes ways of instantiation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ways of instantiation" Watch "ways of instantiation" New topic

ways of instantiation

Jeevan Reddy
Ranch Hand

Joined: Nov 10, 2009
Posts: 142

I was asked this question which I could not answer.
What are the different ways of instantiation in Java?

One of the ways is using "new" and I stopped at that saying I was not sure.

If anyone has an idea please clarify.


SCJP 1.6 (94%)
Karthik Shiraly

Joined: Apr 04, 2009
Posts: 873


1) Class.newInstance() [reflection API] is another method. ex: Object o = Class.forName("someclass").newInstance();

2) Object.clone() creates instances.

3) Autoboxing of primitive types creates instances. ex: Integer n = 25000;

4) ObjectInputStream.readObject() also creates instances, but its implementation probably involves reflection itself.
Jeevan Reddy
Ranch Hand

Joined: Nov 10, 2009
Posts: 142
Thanks Karthik, that is really helpful
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46348
Please search for this; such a question comes up frequently. Particularly in the "beginning Java" forum, where I shall take the liberty of moving this thread (I hope you don't mind, Henry).

Two more examples:
  • A String like "Campbell" is an object in its own right.
  • An array initialiser, eg int[] numbers = {1, 2, 3};
    I agree. Here's the link:
    subject: ways of instantiation
    It's not a secret anymore!