Something like this:
Class Object{
Object(Object obj){}
}
When do you need to do that? I just like to know an example or two.
Mainly used for copy constructor. An example can be as follows:
Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own.
class Complex {
private double re, im;
// A normal parametrized constructor
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}
...
You can refer here for more info.
This can be an effective way of duplicating an existing object or modifying one slightly.
I once worked on a Checkers board game project where Board and Move were represented as classes. In order to create a new game board the class Board had a constructor that accepted another Board instance as well as a Move instance. The constructor made a new game board that would exist if the Move had been applied to the original board.
That is just one example.
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