Nrusingha
Nrusingha

Reputation: 853

java constructor best practice

What is the advantage of having constructor simillar to the one mentioned below:-

class A{
public A(A a){}
public A(){}
}

Upvotes: 1

Views: 1236

Answers (6)

Johan Sjöberg
Johan Sjöberg

Reputation: 49237

It could also be useful in a number of delegation-based design patterns such as decorator or proxy etc.

Providing a default constructor might still be considered good practice, especially in scenarios where dependency injection or serialization are considered.

Upvotes: 0

JasCav
JasCav

Reputation: 34652

As others have said, you have a copy constructor. There are a number of reasons why you may want a copy constructor. Some of those are:

  1. You can provide an alternative to the clone method. (Which is implemented via the Clonable interface.)
  2. Copy constructors are easily implemented.
  3. You can use another constructor to build the copy (by extracting data from the original object and forwarding to a regular constructor).

Check out the link I added to this post for more information about copy constructors and why you would want to use them (if you need them).

Upvotes: 2

Greg L.
Greg L.

Reputation: 306

There is no advantage unless you need to have a copy constructor. I would suggest using the clone() method if this object should be clonable rather than using a copy constructor semantic.

Upvotes: 1

hvgotcodes
hvgotcodes

Reputation: 120308

You're question is very unclear, but basically if you hava a class, that has a constructor, that takes an instance of the same class, then you have a copy constructor. i.e. a constructor that creates a new instance with the same internal values as the original.

Edit -- assuming of course that your constructor does something other than just create a new instance.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240966

A(A a){/*do something*/} Can be helpful as copy constructor.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503519

If you mean the one with the parameter, there's no reason for having that at all, given that it completely ignores the parameter, and there's already another constructor with the same effect.

If you can give a more realistic example, we may be able to give more useful information...

Upvotes: 3

Related Questions