Java Constructor Constructor

I was reading open source, and there was a constructor created like this:

public class FeatureSequence2FeatureVector extends Pipe implements Serializable
{
    boolean binary;

    public FeatureSequence2FeatureVector (boolean binary)
    {
       this.binary = binary;
     }

    public FeatureSequence2FeatureVector ()
    {
       this (false);
    }
 }

      

It might just be a trivial preference question, but I would do the following:

public class FeatureSequence2FeatureVector extends Pipe implements Serializable
 {
    boolean binary = false;

    public FeatureSequence2FeatureVector (boolean binary)
    {
       this.binary = binary;
     }
     public FeatureSequence2FeatureVector ()
     {
     }
 }

      

Is there any possible negative result when assigning an initial value to class variables? Would the two methods be nearly equally preferred?

+3


source to share


2 answers


These two methods are not equally preferred.

The original way ensures that all initialization goes through the primary constructor. The second method allows you to use different paths to initialize the object.



In your example, this is pretty trivial. But with the second way, one constructor could be changed to do something different from how the other constructor did, after which how your objects are initialized depends on the chosen constructor.

This question shows a situation in which different paths can cause problems.

+4


source


One of the reasons I've seen developers is for maintainability and future protection.

Let's break it down to another application:

public void foo() {
  this.foo(1);
}

public void foo(int a) {
  this.foo(a, 2, 3);
}

public void foo(int a, int b, int c) {
  // ...
}

      

It is assumed that

foo

performs an exact or similar operation - regardless of overload. However, what if this functionality changed? In your example, you would have to change the functionality for both versions, whereas in the above example, you would only need to change foo(int, int, int)

.




Future protection is something that counts when designing an API, and the above design pattern is often used because of the ability to support one block of code versus 2 or 3 (or how many overloads you have).

Constructors are the same except that they are invoked with this(...)

.

+1


source







All Articles