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

Constructors

Nilesh Srivastava
Ranch Hand

Joined: Aug 29, 2003
Posts: 70
Hi..
Can we call constructors with out creating the instances of the class.
and
Can we call constructors as method calls.
Thanks..
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11311
    
  16

Why would you want to? I always thought the whole POINT of calling a constructor was to create an instance.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

The answer is a qualified "no". Qualified, because you can call one constructor from another without creating multiple instances. If a class has two constructors, one can call the other using "this()" (it has to be the first line of the constructor ;) likewise, you can call a superclass constructor using "super()". But otherwise, no.
If you need to do this, then what you should do instead is break the body of the constructor out into a normal method, and then call that method from the constructor. Then if you need to "call the constructor" you can instead call that other method.
[ October 17, 2003: Message edited by: Ernest Friedman-Hill ]

[Jess in Action][AskingGoodQuestions]
Jeremy Thornton
Ranch Hand

Joined: Feb 21, 2002
Posts: 91
If you want to simulate the effect of calling a constructor that works without creating an instance a static factory method is pretty straightforward.
Often seen with Singleton pattern.
MyClass aMyClass = MyClass.getInstance();
To answer an earlier comment, its quite common to use an object that you don't have a reference to without necessarily creating a brand new one. Consider an array of 50 Boolean (note class not primitive) values all set to false. Do you really want 50 separate objects or 50 references to a single object?
Boolean.getValue( boolean value ) for instance was added to avoid the need to creating a glut of values where two will do.
hope this helps,
Jeremy.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Constructors