简体   繁体   中英

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(){}
}

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...

A(A a){/*do something*/}可以作为复制构造函数。

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).

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.

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. ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM