Is it possible in Java to initialize a finite data element based on a constructor call?

Is it possible to make the modification specified in the class below and initialize the element for existing subscribers for a specific default value, for example null ?

The member must be private final as a persistence requirement.

 // initial version of the class public class A { A() { // do some work here } } // the following modification required adding additional constructor to the class with **member** data member. public class A { private final String member; A(String member) { this(); this.member = member; } A() { // initilize member to null if a client called this constructor // do some work here } } 
+4
source share
3 answers

Why can't you just:

 public class A { private final String member; A(String member) { this.member = member; } A() { this(null); } } 

This is a common template for a chain of constructors; have less specific versions that invoke more specific versions, supplying default parameters by default.

+6
source

Yes!

 public class A { private final String member; A(String member) { this.member = member; // do some work here instead } A() { this(null); } } 
+5
source

Yes, this is usually used in Enums.

0
source

All Articles