i just begin to learn the hole theory of java for scjp. in documentation i found that is allowed to have an constructor that have as parameter an object of the same class.
What is the logic of this since in my logic you cant do that because to have an object of that class you need to use a constructor and since you have a constructor already the default constructor cant any more accessed.
It might seem strange at first, but remember that classes can have more than one constructor, giving you another way of creating your first instance. Even if it doesn't, you can always pass a null value in. So there's no particular reason why this should be prevented.
And, as Lalit says, there are situations where it's very useful.
Lalit Mehra wrote:for your question: Is it Possible ???
you should try and run it yourself
an object of the same class as the reference can be used in many cases... most common one might be to initialize the new object with the same values as that of the passed one.
Yes but lets imagine this to create an object you need first initialise it for that you need a constructor. Now the logic
if you have an object of type B for example its very logical to use it to initialise another object with this object because in the mean time you done some operations on that object and have very different values in it compared with the values in provided by constructor.
Now if you have only 1 constructor in that class the constructor test(test b) you reach in the paradox egg and chicken who is first.
The problem you cant have an object test because the constructor need to create that object an object of that type.
So how can this be solved?
This is called a copy constructor, and is a way of creating an object identical to that passed. Can be useful for getting copies of mutable objects. Note this example doesn't allow null as a parameter.