Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

creating object

 
kaushik saha
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible in java to create an object without using new keyword.
If it is then how is it possible?
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More of a beginner's question.

Yes.

Use a factory method.

. . . or something like that.
[ March 20, 2007: Message edited by: Campbell Ritchie ]
 
Urs Waefler
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Have a look at the following source code:


class A {

public static void main (String [] args) {

int [] B = new int [2];
B [0] = 5;
B [1] = 6;

int [] C = {7,8};

}
}


An array is an object. There are two arrays. There is an explicit memory allocation. This is array B. There is an implicit memory allocation. This is array C.

Regards
Urs
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


That works because the compiler treats Strings specially.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do some searching on Java reflection and serialization. Let us know if you find more ways to create object instances.
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can create objects without using the new operator atleast in the following ways.

1. Reflection
2. Serialization
3. getInstance() method but that would most probably be using the constructor somewhere.
4. Cloning

There might exist other ways also.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic