Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors

 
Nilesh Srivastava
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12183
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would you want to? I always thought the whole POINT of calling a constructor was to create an instance.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jeremy Thornton
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic