Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: common code for all constructors?
    text
    copied!<p>It seems to me constructors can share the same code, for example in:</p> <pre><code>public class Foo { private int foo; {foo = 5;} public Foo(){} public Foo(int v){this.foo = v;} public int getFoo(){return foo;} } </code></pre> <p>The code "foo=5;" is called for both constructors.</p> <p>It seems to me you can not, but I want to make sure. It not possible to create such common code that use parameters ?</p> <p>eg, something like:</p> <pre><code>public class Foo { private int foo; (int m){foo = m*5;} public Foo(int m){} public Foo(int v,int m){this.foo = v;} public int getFoo(){return foo;} } </code></pre> <p>To my understanding, the only way is to create a private void init(int m) to be called by all constructors ?</p> <p>ps: I call {foo = 5;} "common code", but I guess this feature has another official name ?</p> <p>EDITS (1):</p> <ol> <li><p>The term I was looking for is initializer block</p></li> <li><p>This question is not the same as asking if a constructor can also call another constructor. Because when using an initializer block, the code is called AUTOMATICALLY, ie. without risk to call a constructor and forget to call it</p></li> <li><p>My comment about using "void init" was not good, indeed in this case calling another constructor is better.</p></li> <li><p>In short, my question: can an initializer block takes parameters ? Which would be kind of the same as forcing some parameters on all constructors to be implemented.</p></li> </ol> <p>EDITS (2):</p> <p>I now wonder if the only way to achieve what I am asking is to use inheritance to force the use of a specific constructor.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload