Is there any use in setting instance variables when calling its constructor, rather than in the constructor?

For example:

public class Foo {
    private int bar = 42;

    Foo() {}
}

vs

public class Foo {
    private int bar;

    Foo() {
        bar = 42;
    }
}

Are there any costs / benefits between these two methods? The only way I could see that it matters is in such a scenario (where you set the value twice for the second constructor):

public class Foo {
    private int bar = 42;

    Foo() {}

    Foo(int in) {
        bar = in;
    }
}

vs (where you both install it once)

public class Foo {
    private int bar;

    Foo() {
        this(42);
    }

    Foo(int in) {
        bar = in;
    }
}

Am I missing something? Is there any inherent value in this, anyway?

Edit

Well, I understand that they are functionally equivalent. I am trying to find out if there are significant processing costs associated with one over the other. It seems that at best it should be careless, but I would like to confirm my suspicions.

Edit 2

, . . , , .

+3
5

. :

  • , , , , , , ;
  • .

(2) , :

public class Foo {
    private int bar;

    Foo() {
        this(42);
    }

    Foo(int in) {
        bar = in;
    }
}

DRY ( ), , , . . .

( , ):

public class Foo {
    private final int bar;

    Foo() {
        this(42);
    }

    Foo(int in) {
        bar = in;
    }
}

, ( , ).

+11

. , , . , , , .

Java . . , , :

 public class Foo {
   private int bar;

   //initializer block
   {
      //initializing code here
   }

   Foo() {

   }
 }

, , - , cletus.

+2

, , var.

0

- .

My own (unscientific) experience with legacy Java code is that if there are more than two constructors and more than two fields, 80% of the time something will not be correctly initialized.

0
source

There is a slight difference when your member variables are final and you have a method called from the parent constructor (which is the practice of BAD, please do not do this).

The output code is below:

early = 42
late = 0

Here is the test code:

class Test {

    private static class Base{

        Base() {
            doInConstructor();
        }

        protected void doInConstructor() {

        }
    }

    private static  class Derived extends Base {
        final int early = 42;
        final int late;

        Derived() {
            late = 84;
        }

        protected void doInConstructor() {
            super.doInConstructor();
            System.out.println("early = " + early);
            System.out.println("late = " + late);
        }
    }

    public static void main(String[] args) {
        new Derived();
    }
}
0
source

Source: https://habr.com/ru/post/1710419/


All Articles