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).

Similar Messages

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Set fields of derived class in base class constructor via reflection?

    Does the Java Language Specification explicitly allow setting of fields of a derived class from within the base class' constructor via reflection? The following test case runs green, but I would really like to know if this Java code is compatible among different VM implementations.
    Many thanks for your feedback!
    Norman
    public class DerivedClassReflectionWorksInBaseClassConstructorTest extends TestCase {
    abstract static class A {
        A() {
            try {
                getClass().getDeclaredField("x").setInt(this, 42);
            } catch (Exception e) {
                throw new RuntimeException(e);
    static class B extends A {
        int x;
        B() {
        B(int x) {
            this.x = x;
    public void testThatItWorks() {
        assertEquals(42, new B().x);
        assertEquals(99, new B(99).x);
    }

    why not just put a method in the superclass that the subclasses can call to initialize the subclass member variable?In derived classes (which are plug-ins), clients can use a field annotation which provides some parameter metadata such as validators and the default value. The framework must set the default value of fields, before the class' initializer or constructors are called. If the framework would do this after derived class' initializer or constructors are called, they would be overwritten:
    Framework:
    public abstract class Operator {
        public abstract void initialize();
    }Plug-In:
    public class SomeOperator extends Operator {
        @Parameter(defaultValue="42", interval="[0,100)")
        double threshold;
        @Parameter(defaultValue="C", valueSet="A,B,C")
        String mode;
        public void setThreshold(double threshold) {this.threshold = threshold;}
        public void setMode(String mode) {this.mode = mode;}
        // called by the framework after default values have been set
        public void initialize() {
    }On the other hand, the default values and other metadata are also used to create GUIs and XML I/O for the derived operator class, without having it instantiated. So we cannot use the initial instance field values for that, because we don't have an instance.

  • Events in Class Constructors

    Hi All,
    I would like to know if events (instance/static) can be raised within class constructors. My understanding is that events can be raised but not of the same class as the class constructor belongs to.
    Please clarify.
    Thanks and Regards,
    Vidya.

    Hi Vidya,
    Welcome to SDN.
    see this link
    http://help.sap.com/saphelp_nw04/helpdata/en/41/7af4eca79e11d1950f0000e82de14a/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/0a/b552f7d30911d2b467006094192fe3/frameset.htm
    http://help.sap.com/saphelp_nw04s/helpdata/en/41/7af4eca79e11d1950f0000e82de14a/frameset.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/08/d27c03b81011d194f60000e8353423/content.htm
    for Implementing constructor outside class implementation..  
    use this code
    codeREPORT zkarthik.
    CLASS counter DEFINITION
    CLASS counter DEFINITION.
    PUBLIC SECTION.
    *METHODS CONSTRUCTOR.
    CLASS-METHODS: set IMPORTING value(set_value) TYPE i,
    increment,
    get EXPORTING value(get_value) TYPE i.
    PRIVATE SECTION.
    CLASS-DATA count TYPE i.
    NO explicit constructor
    *METHOD CONSTRUCTOR.
    *WRITE:/ 'I AM CONSTRUCTOR DUDE'.
    *ENDMETHOD.
    ENDCLASS. "counter DEFINITION
    CLASS counter IMPLEMENTATION
    CLASS counter IMPLEMENTATION.
    METHOD set.
    count = set_value.
    ENDMETHOD. "set
    METHOD get.
    ENDMETHOD. "get
    METHOD increment.
    ENDMETHOD. "increment
    ENDCLASS. "counter IMPLEMENTATION
    DATA cnt TYPE REF TO counter.
    START-OF-SELECTION.
    Implicit constructor is called
    CREATE OBJECT cnt.
    CALL METHOD counter=>set
    EXPORTING
    set_value = 5.
    END-OF-SELECTION.[/code]
    happy learning.
    thanks
    karthik

  • How to inherit super class constructor in the sub class

    I have a class A and class B
    Class B extends Class A {
    // if i use super i can access the super classs variables and methods
    // But how to inherit super class constructor
    }

    You cannot inherit constructors. You need to define all the ones you need in the subclass. You can then call the corresponding superclass constructor. e.g
    public B() {
        super();
    public B(String name) {
        super(name);
    }

  • More:Could u pls complete the following code by adding a class constructor?

    Thank you for your concern about my post. Actually it is an exercise in book "Thinking in Java, 2nd edition, Revision 12" chapter 8. The exercise is described as below:
    Create a class with an inner class that has a nondefault constructor. Create a second class with an inner class that inherits from the first inner class.
    And I make some changes for the above exercise requiring the class which encloses the first inner class has a nondefault constructor.
    There is something related to this topic in chapter 8 picked out for reference as below:
    Inheriting from inner classes
    Because the inner class constructor must attach to a reference of the enclosing class object, things are slightly complicated when you inherit from an inner class. The problem is that the �secret?reference to the enclosing class object must be initialized, and yet in the derived class there�s no longer a default object to attach to. The answer is to use a syntax provided to make the association explicit:
    //: c08:InheritInner.java
    // Inheriting an inner class.
    class WithInner {
    class Inner {}
    public class InheritInner
    extends WithInner.Inner {
    //! InheritInner() {} // Won't compile
    InheritInner(WithInner wi) {
    wi.super();
    public static void main(String[] args) {
    WithInner wi = new WithInner();
    InheritInner ii = new InheritInner(wi);
    } ///:~
    You can see that InheritInner is extending only the inner class, not the outer one. But when it comes time to create a constructor, the default one is no good and you can�t just pass a reference to an enclosing object. In addition, you must use the syntax
    enclosingClassReference.super();
    inside the constructor. This provides the necessary reference and the program will then compile.
    My previous post is shown below, could you help me out?
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //Could you please help me complete the following code by generating
    // the Test class constructor to ensure error free compilation? Please
    // keep the constructor simple just to fulfill its basic functionality
    // and leave the uncommented part untouched.
    class Outer {
    Outer (int i) {
    System.out.println("Outer is " + i);
    class Inner {
    int i;
    Inner (int i) {
    this.i = i;
    void prt () {
    System.out.println("Inner is " + i);
    public class Test extends Outer.Inner {
    // Test Constructor
    // is implemented
    // here.
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    Test(Outer o, int i) {
      o.super(i);
    }Note that this doesn't quite answer the question from Thinking In Java, since your Test class is not an inner class (though there is no difference to the constructor requirements if you do make it an inner class).

  • Is it possible to override super class constructor?

    Is it possible to override super class constructor form subclass?

    However, you can achieve do something that looks similar to overriding.
    class Parent {
      Parent(int i, String s) {
        // do stuff
    class Child extends Parent {
      Child(int i, String s) {
        super(i, s);
        // do Child stuff here
    new Parent(1, "abc");
    new Child(2, "xyz");Although that's not overriding, it sort of looks similar. Is this what you were talking about?

  • Reference to enclosing instance in inner class constructor

    Is there any Java compiler which assigns reference to enclosing instance in constructor of inner clase before invoking super class constructor?
    class Outer {
    class Inner extends Global {
    public Inner(int x) {
    // I want (Outer.this != null) here
    super();
    class Global {
    public Global(int x) {

    class Outer {
    class Inner extends Global {
    public Inner(int x) {
    // I want (Outer.this != null) hereOuter.this is never null at this point. A non-static
    inner class always has an implicit reference to an
    instance of the enclosing class.Try this:
    class Outer {
    int m;
    class Inner extends Global {
    public Inner(int x) {
    super(x);
    protected void init(int x) {
    xxx = Outer.this.m + x; // Null pointer exception!!!
    class Global {
    int xxx;
    public Global(int x) {
    init(x);
    protected void init(int x) {
    xxx = x;

  • Constructor and Class constructor

    Hi all
    Can any one explain me the functionality about Constructor and class constructor??
    As well as normal methods, which you call using CALL METHOD, there are two special methods
    called CONSTRUCTOR and CLASS_CONSTRUCTOR, which are automatically called when you
    create an object (CONSTRUCTOR) or when you first access the components of a class
    (CLASS_CONSTRUCTOR)
    I have read the above mentioned document from SAP Documents but i found it bit difficult to understand can any one please help me on this??
    Thanks and Regards,
    Arun Joseph

    Hi,
    Constructor
    Implicitly, each class has an instance constructor method with the reserved name constructor and a static constructor method with the reserved name class_constructor.
    The instance constructor is executed each time you create an object (instance) with the CREATE OBJECT statement, while the class constructor is executed exactly once before you first access a class.
    The constructors are always present. However, to implement a constructor you must declare it explicitly with the METHODS or CLASS-METHODS statements. An instance constructor can have IMPORTING parameters and exceptions. You must pass all non-optional parameters when creating an object. Static constructors have no parameters.
    Class Constructor
    The static constructor is always called CLASS_CONSTRUCTER, and is called autmatically before the clas is first accessed, that is before any of the following actions are executed:
    Creating an instance using CREATE_OBJECT
    Adressing a static attribute using ->
    Calling a ststic attribute using CALL METHOD
    Registering a static event handler
    Registering an evetm handler method for a static event
    The static constructor cannot be called explicitly.
    For better understanding check the following code:
    REPORT  z_constructor.
          CLASS cl1 DEFINITION
    CLASS cl1 DEFINITION.
      PUBLIC SECTION.
        METHODS:
          add,
          constructor IMPORTING v1 TYPE i
                                v2 TYPE i,
          display.
        CLASS-METHODS:
         class_constructor.
      PRIVATE SECTION.
        DATA:
        w_var1   TYPE i,
        w_var2   TYPE i,
        w_var3   TYPE i,
        w_result TYPE i.
    ENDCLASS.                    "cl1 DEFINITION
          CLASS cl1 IMPLEMENTATION
    CLASS cl1 IMPLEMENTATION.
      METHOD constructor.
        w_var1 = v1.
        w_var2 = v2.
      ENDMETHOD.                    "constructor
      METHOD class_constructor.
        WRITE:
        / 'Tihs is a class or static constructor.'.
      ENDMETHOD.                    "class_constructor
      METHOD add.
        w_result = w_var1 + w_var2.
      ENDMETHOD.                    "add
      METHOD display.
        WRITE:
        /'The result is =  ',w_result.
      ENDMETHOD.                    "display
    endclass.
    " Main program----
    data:
      ref1 type ref to cl1.
    parameters:
      w_var1 type i,
      w_var2 type i.
      start-of-selection.
      create object ref1 exporting v1 = w_var1
                                  v2 = w_var2.
       ref1->add( ).
       ref1->d isplay( ).
    Regards,
    Anirban Bhattacharjee

  • Don't need call to super class constructor

    Hi, I have
    class A {
    public A() { System.out.println("in A()");}
    public class B extends A
    { public B() {
    System.out.println("in B()");}
    public static void main( String args[] ) {
    B b = new B();}
    I don't want the super class constructor to be called... What to do? Please tell me solution other than usage of parameterised constructor?

    I don't want the super class constructor to be called... What to do? Can't be done. One of the constructors of the super class must be invoked. (Implicitly or explicitly)
    Kaj

  • Can defualt inherited the Super Class constructor to sub class ?

    Hi,
    is it passible to inherit the super class constructor by defualt when extends the super class.
    Thanks
    MerlinRoshina

    Constructor rules:
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • Calling Nested Class Constructor from main()

    Consider the following code:
    public class OuterClass {
        static static void main(String[] args) {
            NestedClass nc = new NestedClass()
        class NestedClass {
            NestedClass() {
                 //constructor logic here
    }This call to the nested class constructor gives the following error: " 'OuterClass.this' cannot be referenced from a static context. However, if I cut and paste the code for NestedClass into its own class file, there are no error messages. I would like to be able to keep the class nested, so what do I need to do?

    static static void main(String[] args) {
    NestedClass nc = new NestedClass()
    }public static void main(String[] args) {
    NestedClass nc = new NestedClass()
    }

  • Flash CS5 - code hinting doesn't show custom class constructor parameters

    Hi I've got other strange problem my code hinting works almost fine the  problem is that when I create my custom class object code hinting  doesn't show what kind of parameters can be passed to the class  constructor. It shows only "MyClass()", when i call a method like this  class_object.methodName( - parameters show correctly. What can be the  problem?

    I do not work for Adobe, just a fellow forum dweller.
    The example was made quickly because you said this:
    I've tried flash builder but if there is a way to associate code directly from it to symbols on the timeline I haven't been able to find it.
    Now you know how.
    I'm sorry but I don't even have Flash CS6. I still use CS5.5 because I use Flash Builder 4.6 for everything I do. I merely use Flash Pro to generate quick libraries full of goodies and export a SWC to use in Flash Builder.
    I realize it's obvious but you did ensure your preferences had hinting both enabled and the delay set low (or zero)? I can only show you a CS5.5 preference panel, I'm not sure if it's the same. Note one important thing in this photo which is "Cache size". I have mine on 800 files which seems to be fine. If you're pointing toward a HUGE library of classes you may want to increase that number and check completion again.

  • 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");
        );

  • Class Constructor?

    I have a class(arrayList) and an interface(ListInterface) and I'm making a new class called Set(like for numbers and stuff) and I want the constructor for the set to just basically make a new List, but I want to use ListInterface instead of arrayList because I want to be able to use Linked Lists later on, so do you guys have any idea to write the constructor?
    this is the code for Set/the constructor, but it doesn't work and I have no idea what I'm doing wrong...any help?
         private ListInterface data;   // The ADTList to hold the set elements.
          * Initializes an empty set.
         public Set()
              ListInterface data = new ListInterface;
         }

    I suppose you can use reflection, but what's the point? The code isn't set in stone, is it?
    Just make certain that you declare the field in question by its ADT, and that the only part that you name a concrete class is when you instantiate it. Then you'll only have that one line of code to change later.

Maybe you are looking for

  • HP P1006 LaserJet printer and G4 Tiger computer - printing problems

    Help. I bought a new HP P1006 LaserJet printer for a friend that has a G4 Computer that is running Tiger (10.4.11). I set everything up. I tried to print "one" page, to make sure all was well. Well...all was NOT well. It took nearly 4-5 minutes to pr

  • Pls Help - Change over from G5 to Core 2 Duo

    I have just purchased a Intel Core 2 Duo iMac and my old G5 imac, I want to re-install tiger to its factory settings. The problem being that the disc that came from the computer is missing and the installation discs I have a from my new Core 2 Duo. T

  • Trying to connect HP1020 to new MacBook air

    Hello, I'm trying to connect my HP Laserjet 1020 to my new MacBook Air. I have a cable so it's not wireless. It's an excellent printer, has served me for years and I really don't have the money to buy a new one. Is there any way I can use the printer

  • Is there an alterative to that cumbersome alphabet page and remote, such as hooking up a keyboard?

    Using the alphabet screen on the display and clicking each letter to search, put in password, etc., is cumbersome.  Is there an alternative system, such as hooking up a keyboard?

  • E-Filing

    I Have the the E-filing XI content in my Integartion Repository.While opening the Communication channel teplate iit is giving the message as software component version with GUID b38bcd00............... does not exit. what might be the reason what I h