Results 1 to 4 of 4
  1. #1
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    4

    Default Difference between initalization block and data members

    Java Code:
    public class MainFrame extends JFrame{
    	JButton rollButton = new JButton("Roll Dice");
    	JButton clearButton; 
    
    	{
    		clearButton = new JButton("Clear ");
    
    	}
    //some more code..
    }
    What would be the differences between these ?

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default Re: Difference between initalization block and data members

    Both buttons are created and assigned to the variables when an instance of MainFrame is created. The form with the braces (a block) is called an "instance initializer". See JLS 8.6.

    The assignment in the block gets carries out *after* the MainFrame's superclass constructor has been called but *before* the rest of any MainFrame constructor. The gruesome details of what happens when an instance is constructed, and in what order is in JLS 12.5 Creation of New Class Instances.

  3. #3
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    4

    Default Re: Difference between initalization block and data members

    Thanks.

    So not a HUGE difference then...

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default Re: Difference between initalization block and data members

    No.

    I don't think I've ever used an instance initialiser. Others here who are real programmers may know of occasions when it's better than, say, having some initalisation code that is common to a number of constructors. (For a single line like you have, there is no difference at all, I think.)

Similar Threads

  1. Replies: 1
    Last Post: 04-19-2011, 05:32 PM
  2. Accessing abstract class subclass's data members
    By Claymz in forum New To Java
    Replies: 23
    Last Post: 04-18-2011, 12:26 PM
  3. Sharing Data Members between two JFrames
    By PrinceSendai in forum AWT / Swing
    Replies: 3
    Last Post: 10-17-2010, 03:51 AM
  4. private data members?
    By blueduiker in forum New To Java
    Replies: 10
    Last Post: 01-19-2010, 12:13 PM
  5. Hello to all members!
    By tmdurand in forum Introductions
    Replies: 3
    Last Post: 01-18-2009, 03:54 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
  •