Results 1 to 3 of 3
  1. #1
    carl is offline Member
    Join Date
    Jul 2007
    Posts
    35
    Rep Power
    0

    Default Java constructor method

    Hi, So I got a Java constructor question...suppose I am creating a GUI through a constructor like so:
    Java Code:
    public EmailFrame()
    {
    // SETS UP THE UI HERE
    }
    Now I am required to create a similar GUI but with certain fields different...like the window title of the frame for example and so I create a constructor like so:
    Java Code:
    public EmailFrame(String windowTitle)
    {
    // SETS UP THE UI HERE + THE CODE FOR THE TITLE
    So now we have a bad programming situation here. I have a default constructor that does not take any arguments but the code is similar to the other constructor that does take an argument and everything is the exact same other than the one line that deals with the window title.

    How do I go about so that I don't have to re-call the code of the first constructor with minimal work? I have some ideas but before I try I would like to receive some feedback.
    Thanks.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    One way is to send a default value on to the next constructor, viz, the constructor with the next higher number of arguments.
    Java Code:
    public EmailFrame()
    {
        this(null);
    }
    
    public EmailFrame(String windowTitle)
    {
        // SETS UP THE UI HERE + THE CODE FOR THE TITLE
    }

  3. #3
    brianhks is offline Senior Member
    Join Date
    Jul 2007
    Posts
    135
    Rep Power
    0

    Default

    I'd do it a little different
    Java Code:
    public EmailFrame()
    {
        this("Default window title");
    }
    
    public EmailFrame(String windowTitle)
    {
        // SETS UP THE UI HERE + THE CODE FOR THE TITLE
    }
    The other viable option is to put the GUI setup in a private init method and then both constructors call it.

Similar Threads

  1. Replies: 0
    Last Post: 12-19-2007, 09:10 AM
  2. Replies: 0
    Last Post: 12-19-2007, 09:01 AM
  3. Differences between constructor and method
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-19-2007, 08:53 AM
  4. Help with constructor in java
    By mathias in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 01:00 AM
  5. The main method in java...
    By lenny in forum New To Java
    Replies: 1
    Last Post: 07-31-2007, 06:21 AM

Posting Permissions

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