Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to forcefully execute constructors in java ?

 
Kanchan Ghosh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Is there any way to execute the constructor code forcefully?

Class A {
public A() { // Constructor
System.out.println("Hello");
}
}

Suppose in a block of code we hava instantiated the A class in the following way

......... // some code
.........
A a = new A();

Now after creating the instance of A, can we explicitly execute the code(programatically) in the constructor of A. If anybody knows plzz reply.
Thanks in advance....
 
Gavin Tranter
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constructors are NOT methods, and as such can not be called!

You can do:

The calls to this this() are calls to the class constructor, much like calls to super() are calls to the super class constructor.

However, they MUST be on the first line of the constructor, and thus you can use one or the other NOT both.

Oh, and I am not saying the above code is a good or bad idea, just that it can be done.

G

[ April 11, 2007: Message edited by: Gavin Tranter ]
[ April 11, 2007: Message edited by: Gavin Tranter ]
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Gavin says, a constructor is not a method - it is a special block of code that is called to initialise a new instance of a class. So you can't call a constructor on an existing object as if it is a method.

If you need to re-initialise an existing object, you could put the initialisation code in a method, and call that method from the constructor - then later on you can call the initialisation method.
 
Kanchan Ghosh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Gavin and Jesper for your help......
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gavin,

There is an error in your code, marked bold


this(x,5.5); //There is no such constructor which takes int and //double, instead make it this(x,5.5f);


I think, you make a typo, but we are SCJP guys, this can cost us dear!!!

Thanks for giving detailed example!!!

Regards,
cmbhatt
[ April 11, 2007: Message edited by: Chandra Bhatt ]
 
Gavin Tranter
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh dear an error?
Good catch, I always forget floating point literals are actual doubles and not floats.

Not taken the SCJP exam......yet.

Good catch and thanks.

G
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic