Is it possible to call a constructor for a second time, like this:
public ClassName()
{
Value = 10;
}
public void Reset()
{
// Reset
ClassName();
}
Or is this the only way:
public ClassName()
{
Reset();
}
public void Reset()
{
// Reset
Value = 10;
}
The this keyword in Java is a reference to the object of the current class. Using it, you can refer a field, method or, constructor of a class. Therefore, if you need to invoke a constructor explicitly you can do so, using "this()".
Calling a Constructor You call a constructor when you create a new instance of the class containing the constructor. Here is a Java constructor call example: MyClass myClassVar = new MyClass(); This example invokes (calls) the no-argument constructor for MyClass as defined earlier in this text.
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.
It is possible to call constructor many times by using Reflection because constructor is a kind of special method, so you can call it as a method.
public void Reset()
{
this.GetType().GetConstructor(Type.EmptyTypes).Invoke(this, new object[] { });
}
HENCE: this is not how you should do it. If you want to reset object to some default settings, just make some helper, private method for it, called from constructor also:
public ClassName()
{
Defaults();
}
public void Reset()
{
Defaults();
}
private void Defaults()
{
Value = 10;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With