Results 1 to 10 of 10
  1. #1
    Nazneen Ali is offline Senior Member
    Join Date
    Jul 2011
    Posts
    112
    Rep Power
    0

    Default Initializer block for instance variables

    "The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors."


    I have read this on this tutorial: Initializing Fields (The Java™ Tutorials > Learning the Java Language > Classes and Objects)


    1. I don't get it. What is the need of a constructor when an initializer block is there and doing the work of a constructor, in other words working as an alternative to a constructor?


    2. But the constructor has to has to be invoked when creating the instance. OK! but then what is the need of an initializer block?


    3. "Therefore, this approach can be used to share a block of code between multiple constructors."
    Can somebody please give me an example? I mean I don't get it.


    Thank you in advance.
    Don't forget to smile :-)

  2. #2
    Nazneen Ali is offline Senior Member
    Join Date
    Jul 2011
    Posts
    112
    Rep Power
    0

    Default Re: Initializer block for instance variables

    I am trying something like this.

    Java Code:
    package initializer_blocks;
    
    public class Test {
    	
    	int aw, bx, cy;
    	
    	public Test(int a, int b){
    	}
    	
    	public Test(int a, int b, int c){
    	}
    
    
    	
    	public static void main(String [] args){
    		Test t2= new Test(1,2);
    		Test t3= new Test(3,4,5);
    		
    		{
    			t2.aw=a; /// confusion
    			//confusion
    		}
    	}
    Can somebody please tell me where to write initializer blocks and how to assign values to the instance variables in them so that the java compiler copies them into the contructors and thus it saves the repetition of code.

    1. The instance variables have different values for different instances. So I can not directly assign a value to my variable inside an initializer block, because if i have to do that (i.e.) do something as follows, how am I avoiding repetition of code.
      Java Code:
      {
                      t2.aw=1;		t2.bx=2;
      		t3.aw=3;
      		t3.bx=4;
      		t3.cy=5;
                }
    Don't forget to smile :-)

  3. #3
    Nazneen Ali is offline Senior Member
    Join Date
    Jul 2011
    Posts
    112
    Rep Power
    0

    Default Re: Initializer block for instance variables

    The instance variables have different values for different instances. So I can not directly assign a value to my variable inside an initializer block, because if i have to do that (i.e.) do something as follows, how am I avoiding repetition of code.
    I have done that, and it gives all o's in the output.

    Java Code:
    package initializer_blocks;
    
    public class Test {
    	
    	int aw, bx, cy;
    	
    	public Test(int a, int b){
    		System.out.println(aw+"\n"+bx+"\n");
    	}
    	
    	public Test(int a, int b, int c){
    		System.out.println(aw+"\n"+bx+"\n"+cy+"\n");
    	}
    
    
    	
    	public static void main(String [] args){
    		Test t2= new Test(1 ,2);
    		Test t3= new Test(3,4,5);
    		
    		{
    			t2.aw=1;
    			t2.bx=2;
    			t3.aw=3;
    			t3.bx=4;
    			t3.cy=5;
    		}
    	}
    }
    OUTPUT: -

    0
    0

    0
    0
    0
    Don't forget to smile :-)

  4. #4
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,309
    Blog Entries
    7
    Rep Power
    20

    Default Re: Initializer block for instance variables

    For one thing: an initialization block can't take parameters; a small nitpick: an iniatialization block isn't 'copied' anywhere, it is only run before the constructor runs (but after the super class constructors have finished).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    Nazneen Ali is offline Senior Member
    Join Date
    Jul 2011
    Posts
    112
    Rep Power
    0

    Default Re: Initializer block for instance variables

    a small nitpick: an iniatialization block isn't 'copied' anywhere, it is only run before the constructor runs (but after the super class constructors have finished).
    Thank you.
    Don't forget to smile :-)

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default Re: Initializer block for instance variables

    Quote Originally Posted by JosAH View Post
    For one thing: an initialization block can't take parameters; a small nitpick: an iniatialization block isn't 'copied' anywhere, it is only run before the constructor runs (but after the super class constructors have finished).

    kind regards,

    Jos
    Not according to that link to the tutorial:
    "The Java compiler copies initializer blocks into every constructor."

    Of course, that's a tutorial, and may not be the way it actually works...:)
    Would need to find the relevant bits of the JLS possibly?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,336
    Rep Power
    5

    Default Re: Initializer block for instance variables

    As soon as Jos posted his nit I went and checked the JLS. The JLS goes into monotonous detail on the propagation of constructor invocations.
    Here's the section if your interested. Chapter*8.*Classes

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,336
    Rep Power
    5

    Default Re: Initializer block for instance variables

    BTW, you can do quite a lot in initializer blocks. I am not advocating this one way or the other, but it demonstrates what
    may not be obvious.

    Java Code:
    foo(new HashMap<Integer, Integer>() {
        { // start of initializer block
            for (int j = 0; j < 10; j++) {
                put(j, j*10);
            }
        }
    });
    
    public void foo(Map<?,?> map) {
        // do something with map
        for (Map.Entry<?,?> entry : map.entrySet()) {
           System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  9. #9
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,309
    Blog Entries
    7
    Rep Power
    20

    Default Re: Initializer block for instance variables

    Quote Originally Posted by Tolls View Post
    Not according to that link to the tutorial:
    "The Java compiler copies initializer blocks into every constructor."

    Of course, that's a tutorial, and may not be the way it actually works...:)
    Would need to find the relevant bits of the JLS possibly?
    Nowhere in the JLS is copying of any code mentioned; w.r.t. initialization code, the following is mentioned in 8.8.7.1

    Quote Originally Posted by JLS
    •Finally, if the constructor invocation statement is a superclass constructor invocation and the constructor invocation statement completes normally, then all instance variable initializers of C and all instance initializers of C are executed. If an instance initializer or instance variable initializer I textually precedes another instance initializer or instance variable initializer J, then I is executed before J. This action is performed regardless of whether the superclass constructor invocation actually appears as an explicit constructor invocation statement or is provided automatically. An alternate constructor invocation does not perform this additional implicit action.
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default Re: Initializer block for instance variables

    Ah, but that's the JLS.
    That doesn't actually cover how the compiler achieves those tasks...:)

    And looking at the bytecode, the compiler does indeed appear to copy that code into each constructor.
    Java Code:
    public class InitTest {
    
    	private int i;
    	{
    		i = 11;
    	}
    	
    	private int q;
    	
    	public InitTest() {
    		q = 1;
    	}
    	
    	public InitTest(int q) {
    		this.q = q;
    	}
    	
    	public InitTest(String anothrt) {
    		initI();
    	}
    	
    	private void initI() {
    		i = 4;
    	}
    }
    Compare the bytecode used for the initialiser with that for the initI call.
    Surprised the compiler doesn't create some form of dummy method, but I expect there's reasons.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Help with instance variables in a method
    By mstratmann in forum New To Java
    Replies: 3
    Last Post: 05-07-2013, 11:13 AM
  2. Instance variables
    By jwl in forum New To Java
    Replies: 2
    Last Post: 10-24-2012, 11:29 PM
  3. Instance Variables
    By TriSBR in forum New To Java
    Replies: 2
    Last Post: 11-16-2011, 04:16 PM
  4. Instance variables
    By lala in forum New To Java
    Replies: 1
    Last Post: 01-26-2011, 04:38 PM
  5. What are Instance variables and static variables?
    By sandeshforu in forum New To Java
    Replies: 3
    Last Post: 09-09-2009, 05:48 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •