OPK
OPK

Reputation: 4180

What is the use for a constructor take the same type as a parameter? Java

Something like this:

Class Object{

    Object(Object obj){}

}

When do you need to do that? I just like to know an example or two.

Upvotes: 3

Views: 1012

Answers (4)

Darshan Lila
Darshan Lila

Reputation: 5868

Well here's what you should know about following code:

class Object{

    Object(Object obj){}

}

Class Object has a constructor which takes a argument of class of type Object. You can use Object as following:

class MainClass{
 public static void main(String args[]){
    Object obj=new Object(new Object());
  }
}

Here an anonymous object of Object class is passed to Object constructor.

Upvotes: 0

Nabin
Nabin

Reputation: 11776

Basically when a class needs to return an object of its own type when made.

class Player{
    int jerseyNumber;
    Player(){

    }
    Player (Player p){
        this.jerseyNumber = p.getJerseryNumber();
    }

    int getJerseryNumber(){
        return jerseyNumber;
    }
void setJerseyNumber(int jerseyNumber){
    this.jerseyNumber = jerseyNumber;
}
}

And you can do this.

Player ponting;
ponting.setJerseyNumber(14);
Player somebodyelse(ponting);

This helps to make a new object from properties of existing one. So basically this is called Copy constructor.

Upvotes: 0

CorbinMc
CorbinMc

Reputation: 588

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.

Upvotes: 1

nitishagar
nitishagar

Reputation: 9403

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.

Upvotes: 3

Related Questions