Fields initialization : initializers vs constructors

I've just come to thought that I might be doing the wrong thing using initializers instead of initializing fields in the constructor. Of cause I'm speaking of DPL..
I'm used to do something like this:
@Persistent
class Compound
   private final Map<Integer, Integer> elements = new HashMap<Integer, Integer>();
   private Compound() {} //dummy private default constructor to be used by BDB
   //actual constructor to be used in the code
   public Compound(int initialValue)
     //some specific initialization...
     //e.g.:
     elements.add(initialValue, initialValue);
}But while thinking about what will BDB actually do when demarshaling the object instance, I came to idea that it would re-construct the elements map and forget the one I carefully create in the initializer.. So to avoid the useless object instantiation I'd have to initialize the field in constructor like this:
@Persistent
class Compound
   private final Map<Integer, Integer> elements;
   //dummy private default constructor to be used by BDB
   private Compound()
     //now I have to assign something to elements field because it's final..
     // or just remove the *final* modifier???
     elements = null;
   //actual constructor to be used in the code
   public Compound(int initialValue)
     elements = new HashMap<Integer, Integer>()
     //some specific initialization...
     //e.g.:
     elements.add(initialValue, initialValue);
}So my question is: is there any actual difference between the first and second approaches? Or I just thinking the wrong way?..

Hm.. Yes, I'm pretty sure it's working with JE. I was thinking that reflection allows bypassing the "final" modifier.. Hm.. Quick googling gives this for example: http://stuffthathappens.com/blog/2007/10/13/you-can-change-final-fields/. While reading this article it seems that it's still a bad idea to rely on it..
Interesting, thanks. I was probably remembering tests I performed on Java 1.4, which does not allow setting final fields, according to one of the comments.
Yes, relying on this behavior can get you into trouble for two reasons.
1. If the field happens to be public, JE will not call setAccessible.
2. If you're using the bytecode annotator, JE does not use reflection to set fields, and the generated code that changes the final field will fail.
The second issue is insidious, if you use the default reflection mechanism during initial development and then switch to bytecode generation later on.
I think JE should always throw an exception if the final modifier is set, to guard against this.
--mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Class field initialization outside class constructor

    Hi,
    what are the benefits of initializing a class field outside the class constructor? I use this for fields, that i do not need to pass parameter to via the constructor. The code seems more clear/easy to read.

    Hi,
    what are the benefits of initializing a class field
    outside the class constructor? I use this for
    fields, that i do not need to pass parameter to via
    the constructor.
    The code seems more clear/easy to read.That's a pretty big benefit.
    For another, consider when you have multiple constructors: you've factored
    common code out of them (good) and made it impossible to forget to
    initialize that field later when, later on, you write another constructor(also good).

  • Field initialization in Constructor

    Hi
    I have a Question about a Design issue.
    For example, I have a class that stores a Hashtable. This Hashtable should never be null, so it is initialized. I have these two alternatives:
    class Test{
          Hashtable table= new Hashtable();
    class Test{
           Hashtable table;
           public Test(){
                this.table= new Hashtable();
    }So, which approach is better in what Situation? The only difference I see is, that the first example spends time for initialization on class loading, the other on instantiation. Therefore I would rather use the first one.
    What suggestions do you have?

    So, which approach is better in what Situation? The
    only difference I see is, that the first example
    spends time for initialization on class loading, the
    other on instantiation. Therefore I would rather use
    the first one.
    What suggestions do you have?Normally I would use the member initialization.
    The exception to that would be if I expect that the initialization might throw an exception. In that case it is easier to control and understand the exception flow if it is generated by the constructor rather than the class load.

  • Initialize in the constructor is better or set the value thro' set method?

    Hi,
    For the normal helper classes for servelt or jsp or EJB,
    Which of the following one is the better ...?
    1.
    i.initialize all the fields in the constructor, then
    ii.use the set methods
    or
    2.
    i.do not use the contructor and
    ii.use the set methods to set the values
    Anybody can give the solution for this one...
    With regards
    vkm

    Your option 1 puzzles me, why would you need tyo use the setter methods if you already initialized in the constructor?

  • Initialization block vs constructor

    Dear,
    Inside a class in Java, it is possible to declare a block (between '{ }') and declaring it 'static'. This is a 'initialization block' executed once when the class is loaded = before an object of this class is created.
    But this seems to me very close to the functionality of a class constructor function, except this is runned each time the class is instanciated.
    Can somebody give me good examples illustrating when each of them are needed (separately or together) ?
    Is class loading not occuring at the instanciation time of a class (as constructor execution) ?
    Thanks in advance.

    dcminter wrote:
    The USER_ROLES field can be accessed before the containing class has been instantiated (note that class loading and class instantiation are quite different things). If you put that logic into the constructor, you would get an empty set in those circumstances.Iinstead of using the static initializer block in the containing class
    you can put the initialization into the Set using literals
        public static final Set<String> USER_ROLES = Collections.unmodifiableSet(
            new HashSet<String>(Arrays.asList(new String[]{"USER","OWNER","ADMINISTRATOR"}))
        );or using the instance initializer block of the Set
        public static final Set<String> USER_ROLES = Collections.unmodifiableSet(
            new HashSet<String>(){{
                add("USER");
                add("OWNER");
                add("ADMINISTRATOR");
        );

  • Static field initialization

    Ok, I know this was a good practices issue in C++, where order of initializing static fields from different source files was unknown, but I'm not sure if Java is smart enough to figure it out.
    So, say you have in one file
    public class A{
       public static B b = new B();
    }And in the other:
    public class C{
       private static D  d = A.b.getD();
    }Will this always work? Or does it depend on the order in wich classes A and C are loaded.

    jschell wrote:
    In multiple threads on some systems (potentially) the construction of B() is not guaranted before access to 'b' is allowed.Class initialization is synchronized, so the construction of B() should be fully visible to other threads without explicit synchronization or making the field final.
    From JLS 12.4.3:
    Code generators need to preserve the points of possible initialization of a class or interface, inserting an invocation of the initialization procedure just described. If this initialization procedure completes normally and the Class object is fully initialized and ready for use, then the invocation of the initialization procedure is no longer necessary and it may be eliminated from the code-for example, by patching it out or otherwise regenerating the code.So class initialization is attempted whenever the code generator feels it might be the first use of a class.
    And from 12.4.2:
    The procedure for initializing a class or interface is then as follows:
    1. Synchronize (§14.19) on the Class object that represents the class or interface to be initialized. This involves waiting until the current thread can obtain the lock for that object (§17.1).
    2. If initialization is in progress for the class or interface by some other thread, then wait on this Class object (which temporarily releases the lock). When the current thread awakens from the wait, repeat this step.So the class is synchronized on until initialization (which includes all static initializers) finishes. This makes possible the class holder idiom for singletons.

  • Invoking a constructor

    in ibm's tut i found this sentence:
    a constructor can be invoked only from other constructors
    My Q:
    this means you cant invoke a constructor inside itself, or else that you can only incoke a constructor IF you'r inside one?
    thanks in advance

    i guess i got it;
    thanks for helping
    now, i've another Q, pls:
    i got the first class from the same place, and
    created the second in order to see if i understand it
    (the this again)
    class Dot {
    int x, y;
    Dot(int x, int y) {
              this.x = x;
              this.y = y;
    class Z {
    public static void main(String[] args) {
              Dot d = new Dot(16, 17);
              System.out.println(d.x + ", " + d.y);
    }My Q:
    can i say (even in a bit improper way) that the
    this is translated into d, in my
    class?I wouldn't say it that way. Depending on what image you're conjuring up for that, you may be on the right track though.
    When you use "d.x" and "d.y", there's really no "this" involved.
    If you had a method inside Dot void setX(int x) {
        this.x = x;
    } and then called d.setX(42); then while that method is executing, "this" refers to the same object that "d" refers to outside of the method. "d" has some value which is, in essence, the address of an object. That value was copied into "this" when the setX method was invoked.
    When you invoke the constructor, it's a little different. There's still an objet, but at the time the constructor is executing, "d" doesn't point to it yet (okay, technically, it can, but that's a very low-level optimization issue. conceptutally, it's safe to say it doesn't).
    When you called "d.setX" d's value was copied into "this". In the case of the constructor, however, the keywork "new" tells the VM to create an object, initialize its fields, and invoke its constructor. Once the object has been created, its address is copied into "this" for the constructor to use. When the construction operation has been completed, the address of the object is copied into d.

  • How to ensure multiple nested classes static readonly initialization orders

    Hello,
    I am emulating the Java Enumeration in a first class class, with static readonly field initialization.
    In an effort to further categorize some instances, I embed them in nested classes. Something like this.
    class A : Enumeration
    public static class CatB
    public static readonly A FirstInstance = new B();
    public static readonly A SecondInstance = new B();
    public static class CatC
    public static readonly A ThirdInstance = new C();
    public static readonly A FourthInstance = new C();
    class B : A
    class C : A
    So far so good.
    One strain of Enumeration has built-in Ordinals, so I initialize them in the static ctor, or I make an effort to.
    static A()
    var values = GetValues().ToList();
    var ordinal = 0;
    values.ForEach(v => v.Ordinal = ++ordinal);
    Also, in places, so far so good.
    However, in a main method, I am referencing one of the enumerated instances, so calls to my GetValues() is returning nulls for that nested class. The other nested class instances are just fine, they return just fine.
    I could post more, but I think this illustrates the idea.
    I am suspicious that a strange static initialization order is jumbled up, as evidenced by nested static ctor debug statements I put in. I get one print and not the other.
    When I switch up which instance I reference in my main, I get the opposite behavior, more or less confirming my suspicions.
    So... Question is, what's the best way to potentially work around this issue? Hopefully without abandoning the Enumeration concern altogether, but that thought is a possibility as well. Or at least do so differently.
    Thank you...

    It is probably necessary to show GetValues() at least. I am getting the correct nested types, so that much we can at least assume.
    protected static IEnumerable<TDerived> GetValues()
    var declaringTypes = GetDeclaringTypes(typeof (TDerived)).ToArray();
    foreach (var declaringType in declaringTypes.Reverse())
    var fis = declaringType.GetFields(PublicStaticDeclaredOnly);
    var values = fis.Select(fi => fi.GetValue(null)).ToArray();
    foreach (var value in values.OfType<TDerived>())
    yield return value;
    Okay, here a bit of explanation.
    Enumeration is declared generically, with TDerived as the derived type. In this case, A.
    GetDeclaringTypes is operating okay. I get types for A, B, and C.
    The fis to values is breaking down, however. When I reference any of the CatB's, I get nulls for those instances. Conversely, same for CatC's when I reference any of those.

  • I need to grey out the field at 2 locations?

    Hello
    I have page1 and page3 in my_form. Page1 has field with caption 'COUNTRY', Page3 also has the same field (Caption is COUNTRY's NAME), and BINDed with same data source, and the NAME is same in BINDING tab, in both fields NAME is UR_COUNTRY in BINDING tab, fine.
    Requirement is to make it grey out (at 2 locations, its Page 1 and Page 3) and ReadOnly as well, so, i am wring the below Java Script in my_form's docReady event
    my_form.Page1.Address.COUNTRY.access = "readOnly"
    xfa.resolveNode("my_form.Page1.Address.COUNTRY.ui.#textEdit.border.fill.color").value = "192,192,192";
    Its greying out in Page1's COUNTRY field, but NOT greyinh out the Page'3 COUNTRY's NAME field!! not sure why?
    Pls. let me know How can i do it WITH OUT code redenncy (code redenency is not accepting against standards here)?  I do not want to repeate the code again in Page3's COUNTRY's NAME field initialization event
    Thank you

    Hi,
    In your script you are only referencing the object on Page1. If you also want to change the appearance of the object on Page3, then you will need to duplicate the lines and reference that object specifically.
    Also, you can make the fill color script a bit leaner/generic:
    COUNTRY.ui.oneOfChild.border.fill.color.value = "192,192,192";
    Hope that helps,
    Niall

  • What for do we need constructor?

    Hi I just wonder, if I can have construction like this:
    public class MyClass
    private int a = 5;
    private AnotherClass another = new AnotherClass();
    public MyClass()
    //absolutely nothing to do in here
    }which lets me initialize variables directly in class definition what for do we need constructor? I always thought that we should initialize object via constructor but as java lets us do it without constructor what is the point of having one? Except of course to provide a way to tell compiler that we want another object of this class by saying:
    MyClass myClass = new MyClass();Thanks for any answers.

    atch7 wrote:
    Hi I just wonder, if I can have construction like this:
    public class MyClass
    private int a = 5;
    private AnotherClass another = new AnotherClass();
    public MyClass()
    //absolutely nothing to do in here
    }which lets me initialize variables directly in class definition what for do we need constructor? I always thought that we should initialize object via constructor but as java lets us do it without constructor what is the point of having one? Except of course to provide a way to tell compiler that we want another object of this class by saying:
    MyClass myClass = new MyClass();Thanks for any answers.But you do have a constructor. Take your example and do it this way
    public class MyClass {
      private int a = 5;
      private AnotherClass another = new AnotherClass();
    }As you wanted. Okay, you can do this. No problem. The compiler will add a default constructor for you, so, even though you didn't write one, you still have one.

  • This() and super() invocations in constructor bodies

    Hi,
    Could someone please explain why it is not allowed to explicitly
    call this() or super() in a constructor body anywhere as opposed
    to the first statement in the constructor (which in turn implies that
    this() and super() can not be used together) ?
    Also, If the constructor is a constructor for an enum type, it is a compile-time
    error for it to invoke the superclass constructor explicitly. Why ?
    And the last question - why it is not allowed to invoke this() or super()
    with instance fields ?
    Cheers,
    Adrian

    AdrianSosialik wrote:
    Could someone please explain why it is not allowed to explicitly
    call this() or super() in a constructor body anywhere as opposed
    to the first statement in the constructorI think it was a language design decision. One could allow certain statements before invoking another constructor, but this would probably cause more confusion than help. So I guess it was deliberatly chosen to not allow this.
    (which in turn implies that this() and super() can not be used
    together) ?Yes, but if this would be permitted, it would also be harder to guarantee that a superclass constructor gets called exactly once.
    Also, If the constructor is a constructor for an enum type,
    it is a compile-time error for it to invoke the superclass
    constructor explicitly. Why ?Could you provide a "compilable" code snippet that demonstrates this?
    And the last question - why it is not allowed to invoke this()
    or super() with instance fields ?As you are not able to store something in them before the invocation, they contain their default values... (the JVM allows storing values in instance fields before invoking another constructor, but it was apparently decided to not include such a thing in Java)

  • How to get a constructor with parameters

    I got a problem and can not find anywhere my answer, I have a class Sudoku with a 2 dimension arrays(2D) as a parameter.
    public Sudoku(int[][] problem)
    I have another class named SudokuSolver as you can see below.
    public class SudokuSolver
    /** Main method to solve the sudoku problem. */
    public static void main(String[] args)
    Sudoku Sudoku1 = new Sudoku();
    How could I call/initialize the Sudoku constructor in the SudokuSolver class main method?
    If it was without parameters would be like above Sudoku Sudoku1 = new Sudoku();, but when I put the value like Sudoku Sudoku1 = new Sudoku( {{1,2}}); it does not work.
    I would be very happy if anyone could help me out with this noob question.
    7runks.net

    You have to actually declare that it's an array

  • Initializing array constructor to 0

    I have created a stats class, but I am not sure how to initialize the array constructor to be all zeros. It is a single interger array that can hold 50 values.

    int[] array = new int[50];Each array element will be initialized to zero.
    The Java� Tutorial - Arrays

  • Construction (just out of interest)

    After puzzling over this for some time I have concluded that construction must occur sort of in this order:
    memory allocated
    super called
    variables initialised
    constructor body called.
    however after seeing some results I am rather confused. From the following code sample (without arguing whether the code is 'correct') the results have confused me:
    abstract class A {
       C c = new C();
        public A() {
           configure();
           System.out.println("A.A()");
        public abstract void configure();
    public class B extends A {
       String myVar = "INIT";
       public B() {
         super();
         System.out.println("B.B()");
       public void configure() {
        System.out.println("B.configure()");
          myVar = "FOO";
    public static void main(String[] args){
         B b = new B();
         System.out.println("myVar: " + b.myVar);
    class C{
    C(){
      System.out.println("C.C()");
    }printing out
    C.C()
    B.configure()
    A.A()
    B.B()
    myVar: INITso we can assume that when the constructor of B is first entered myVar is already set to "INIT", configure then sets it to "FOO", but when the super constructor exits myVar is reset to "INIT" which seems to suggest that the variable is initialised twice.. giving us an order of:
    memory allocated
    variables initialised
    super called
    variables initialised
    constructor body called.
    Is this correct? And is there a reason for it being done like this? couldn't the JVM just get away with doing?
    memory allocated
    variables initialised
    super called
    constructor body called.
    these results have been observed in 1.4.1_02, is this likely to be different in different JVM's?
    Thanks for your time

    This is what happens:
    Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden. If there is not sufficient space available to allocate memory for the object, then creation of the class instance completes abruptly with an OutOfMemoryError. Otherwise, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values.
    Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:
    # Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.
    # If this constructor begins with an explicit constructor invocation of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 5.
    # If this constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this) and is in a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.
    # Execute the instance variable initializers for this class, assigning their values to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5. (In some early implementations, the compiler incorrectly omitted the code to initialize a field if the field initializer expression was a constant expression whose value was equal to the default initialization value for its type. This was a bug.)
    # Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.

  • Best practice for declaring and initializing String?

    What is the best practice for the way Strings are declared in a class?
    Should it be
    private String strHello = "";
    or should I have the initialization in the constructors?

    The servlet constructor is usually called once, when the servlet is first accessed. But then again maybe something else happens, google servlet life cycle if you must know.
    But let's take a step backwards here. It seems like you are trying to put fields into servlets. Don't do that. When two users fetch the servlet's URL at the same time, the fields are shared between the two hits. If you store something like HTTP parameters in the fields, the two hits' parameters will get mangled. The hits can end up seeing each other's parameter values.
    The best way is not to have fields in servlets. (Except maybe "static final" constants, sometimes rarely something else.) Many concurrency worries go away, servlet life cycle worries go away, servlet constructors go away, init() usually goes away.

Maybe you are looking for