Use method in constructor?

Is it possible to call a method in a constructor if that method belongs to the same class? Will there be problems calling the method since the object hasn't been completely created yet?
Example code:
Class Foo
  // constructor
public Foo()
   method bar();
public void bar()
}In my class, I'd like to initialise some attributes in the constructor. After object creation, that initialisation (which includes some ordening) should also be available as a public method, to re-order my attributes if necessary. I'd like to avoid using double code for the ordering (both in the constructor and in the method).

Is it possible to call a method in a constructor if
that method belongs to the same class?
Yes, but it's often not recommended for the reason you have discovered:
Will there be problems calling the method since the object hasn't
been completely created yet?
This depends on what the method does and at which point you call it. The object has been fully created, it's just not properly initialized. If you call the method after you've set all instance variables to their initial values there should be no problem.
But you should make that method final, private, or static so that it won't be possible to override it from subclasses. If someone writes a subclass that overrides that method, the method will be called before the subclass instance has had any chance to initialize itself which is a likely source of bugs.

Similar Messages

  • Sample Program Using Method And Constructor

    Pls. help me... pls. post just a simple running program... that uses a method and constructor getter and setter..... my program doesn't do anything
    public class Attraction{
         public int minutes;
         public Attraction(){
              minutes = 75;}
         public Attraction(int m){
              minutes = m;}
         public int getMinutes(){
              System.out.println("Reading an attraction's minutes...");
              return minutes;}
         public void setMinutes(int m){
              System.out.println("Writing an attraction's minutes...");
              minutes = 7;}
    }

    public class Attraction{
         public int minutes;
         public Attraction(){
              minutes = 75;}
         public Attraction(int m){
              minutes = m;}
         public int getMinutes(){
    System.out.println("Reading an attraction's
    s minutes...");
              return minutes;}
         public void setMinutes(int m){
    System.out.println("Writing an attraction's
    s minutes...");
              minutes = 7;}
    //new code added
    public static void main(String arg[]){
    Attraction att=new Attraction();
    att.setMinutes(14);
    att.getMinutes();
    }

  • Can we use an overloaded constructor of a Java Bean with Session Tracking

    Hi Friends,
    If any one can solve my query.... It would be helpful.
    Query:
    I have a Java Bean with an overloaded constructor in it. I want to use the overloaded constructor in my JSP.
    1. One way of doing that is to use it directly in the "Scriptlets" (<% %>). But then I am not sure of the way to do session tracking. I think I can use the implicit objects like "session", "request" etc. but not sure of the approach or of the implementation method.
    2. Another way is through the directive <jsp: useBean>. But I cannot call an overloaded constructor with <jsp: useBean>. The only alternative way is to use the directive <jsp: useBean> where I have to write getter and setter methods in the Java Bean and use the <jsp: setProperty> and <jsp: getProperty> standard actions. Then with this approach I cannot use the overloaded constructor.
    Can any one suggest me the best approach to solve this problem ?
    Thanks and Regards,
    Gaive.

    My first reaction is that you can refactor your overloaded constructor into an init(arguments...) method. Instead of overloaded constructor, you can call that init method. This is the ideal solution if possible.
    As to the two choices you listed:
    1. This is OK, I believe. You can use scriplet to define the bean and put it into session scope of the pageContext. I am not sure exactly what you meant by session tracking; whatever you meant, it should be doable using HttpSessionAttributeListener and/or HttpSessionBindingListener.
    2. Agreed. There is no way that <jsp:useBean> can call a constructor that has non-empty arguments.
    Please tell me how it works for you.

  • What is the advantage of using methods to return objects?

    Hello there,
    What is the advantage of using static methods to return
    objects? Isnt this a Factory Pattern ?
    What is the real advantage of using methods to return objects
    rather than using public constructors to create objects ?
    Can some one please explain
    Regards

    I think there were two questions. The first (why
    static) is well answered but I hope somebody can
    answer the general question - why whatever =
    createSomething(); as opposed to whatever
    = new Something(); - because inquiring minds
    want to know.I thought I answered that question. Perhaps I need to be more specific.
    For the Singleton pattern, you don't want a new instance (except possibly the first time, if you're using lazy instantiation).
    For the Factory pattern, you might not always want an instance of the actual class containing the static methods, so new won't work.
    If, on the other hand, neither of the above holds, there is no reason not to use new (unless, of course, anyone can come up with another use of static creators).
    RObin

  • Using @PostConstruct vs constructor initialization

    I've been reading through an EJB 3 book. I've noticed that lots of the examples of stateful session beans use methods marked with @PostConstruct to do member variable initialization instead of just initializing them in the constructor. There must be a reason for this, right?
    Can anybody explain the purpose for this?

    Hi,
    The reason is that in EJB dependency injection (access to resources, other EJBs etc) is done by the container after the constructor is called and before any @POSTCONSTRUCT annotated method is called. Therefor, at the time that a @POSTCONSTRUCT annotated method is executed, the EJB has all dependecies initialized.
    HTH Robert

  • How to trap null return values from getters when using Method.invoke()?

    Hi,
    I am using Method.invoke() to access getters in an Object. I need to know which getters return a value and which return null. However, irrespective of the actual return value, I am always getting non-null return value when using Method.invoke().
    Unfortunately, the API documentation of Method.invoke() does not specify how it treats null return values.
    Can someone help?
    Thanks

    What do you get as a result?I think I know what the problem is.
    I tested this using following and it worked fine:
    public class TestMethodInvoke {
    public String getName() {
    return null;
    public static void main(String args[]) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Object o = new TestMethodInvoke();
    Class cls = o.getClass();
    Method m = cls.getMethod("getName", (Class[]) null);
    Object result = m.invoke(o, (Object[])null);
    if (result == null) {
    System.err.println("OK: Return value was null as expected");
    else {
    System.err.println("FAILED: Return value was NOT null as expected");
    However, when I use the same technique with an EJB 3.0 Entity class, the null return value is not returned. Instead, I get a String() object. Clearly, the problem is the the EJB 3.0 implementation (Glassfish/Toplink) which is manipulating the getters.
    Regards
    Dibyendu

  • How can I use methods of an object with private instantiation in my ABAP?

    Hello all,
    What is the work-around on using methods of an object marked as private instantiation? I tried to use concepts of <b>INHERITANCE</b> or <b>FRIENDS</b> of an object (<u>BCONTACT </u> in my case - a SAP standard object) but it did not work, or at least, I do not know how to properly code the statements in my ABAP program.
    Any code samples, other ideas?
    Your help is greatly appreciated.

    I am closing this question as there has been no answer.
    Message was edited by:
            Goharjou ardavan

  • Java.lang.NoSuchMethodException Using Method.invoke(...)

    I try to use Method.invoke() to invoke a method from a class. The method
    has parameters with type JTextArea and JMyFrame, but I got the error
    messages java.lang.NoSuchMethodException . Any ideas???
    If I remove parameter "JFrame mainFrame" in start() method and it is working fine. Not sure why JMyFrame will throw this exception, as JMyFrame is derived from JFrame class
    public class MyFrame extends JFrame
         try
    ClassLoader loader
    = new MyClassLoader(Integer.parseInt("3"));
    Class c = loader.loadClass("NewMenuPackage.NewMenu");
    Class[] params = { JTextArea.class, JMyFrame.class };
         Method m = c.getMethod("start", params);
         Object obj = c.newInstance();
    m.invoke(obj,
         new Object[] {
              textArea,
              JMyFrame.this
    catch (Throwable e)
    JOptionPane.showMessageDialog(this, e);
    package NewMenuPackage;
    import javax.swing.*;
    public class NewMenu
         private static JMenuItem menuItem = new JMenuItem("New Menu");
         public static JMenuItem getJMenuItem()
              return menuItem;
         public static void start(JTextArea textArea, JFrame mainFrame)
              System.out.println("NewMenu->start()...");
    }

    Your "params" Class array has to specify the exact classes of the method, not subclasses. The line that is causing the NoSuchObjectException to be thrown is "c.getMethod("start", params);".
    You have to write your own reflection utility methods to find a method that matches on parameter subclasses.

  • Error while attaching the document using Method add_attachment

    Hello Friends,
    We are getting an error while using the BCS Class Method for attaching the documents to the mail.
    We are using method:  add_attachment()
    For this I am passing the parameters:
    attachment_type: PDF
    attachment_subject: XXXXXXX
    att_content_hex: content_hex[]  "Internal table
    The system is throwing error message X_ERROR.
    Friends please help me in how to rectify the error message.
    Thanks and Regards
    Pradeep Goli

    Hi,
    Please code as below.
    data: binary_content type solix_tab.
    CALL METHOD Document->add_attachment EXPORTING i_attachment_type = u2018PDFu2019
    i_attachment_subject = u2018My attachmentu2019 i_att_content_hex =
    binary_content.
    Regards
    chitra

  • End of page in ALV using METHODS

    Hi Folks,
    I have to display End of Page in an list which is using
    CALL METHOD grid1->set_table_for_first_display for display.Is there any method in the same way so that I can totals at the end of page in that list.
    For you info I am not using any of the REUSE_ALV_...... function modules in the program.So kindly let me know how to get it using methods.
    Thanks,
    K.Kiran.

    Hello Pratuysh,
    Thanks for the answer
    I know that report,but that doesn't help me.
    Any other way
    Thanks
    Jai

  • Need help using method check_changed_data correctly

    I'm using method check_changed_data in my ALV program to update the grid with changes the user makes. The method works fine for this purpose. But I also want to know if any data actually changed. Can anyone give me an example?
    FORM update_vendor .
    do I need to call a different method before check_changed_data ?
      call method gridhead->check_changed_data.
    is there a parameter available here to see if anything actually
             changed?
      loop at gt_head into wa_head.
        clear wa_head-lifnam.
        select single name1 into wa_head-lifnam
          from LFA1 where lifnr eq wa_head-lifnr.
        if sy-subrc eq 0.
          modify gt_head from wa_head.
        endif.
      endloop.
    ENDFORM.                    " update_vendor

    Hello Beth
    If data have been changed then method <b>go_grid->CHECK_CHANGED_DATA</b> will raise event <b>DATA_CHANGED</b>. If you have an event handler method like HANDLE_DATA_CHANGED then you can, for example, validate the changes.
    If no data were changed event DATA_CHANGED will not be raised and your event handler method will not be called.
    Regards
      Uwe

  • How to use method POST to send XML using utl_http?

    Hi,
    I am trying to work out how to use the POST method to mimic submitting data from a HTML form, using utl_http.
    I cannot use SOAP for this as the people I am sending the data to are just expecting an XML document to be sent to a standard CGI script running on their web server.
    There is a lot of documentation on how to submit data using the POST method (using Utl_Http.Write_Text etc), but I cannot find anything that tells me how to submit form variables.
    The examples on OTN say this:
    "Alternatively use method => 'POST' and Utl_Http.Write_Text to
    build an arbitrarily long message"
    but don't tell me how to actually place the data into the required input parameters of the CGI program I am hitting.
    I need to hit a URL such as
    www.asite.com/cgiprogram
    and pass in a parameter, eg
    in_param="test+data"
    I am currently doing this as a GET, which works, but the XML document I am passing in could potentially be bigger than the GET method will allow.
    Any help would be greatly appreciated.
    Thanks,
    Leon.

    Please try the PL/SQl forum

  • Using methods from another Form C#

    Hello!
    I'm having some trouble using methods from one Form in another one. Here's the deal:
    This is a snippet from my 'main' form:
    public partial class PRINCIPAL : Form
    //some variables here
    Form2 Config = new Form2();
    Form3 Cadastro = new Form3();
    public PRINCIPAL()
    InitializeComponent();
    //code goes on and on
    //Here's the method I want to call on the other forms (Form2 and Form3)
    public void salva_banco()
    this.Validate();
    this.projetoBindingSource.EndEdit();
    this.modulosBindingSource.EndEdit();
    this.funcaoBindingSource.EndEdit();
    this.estadosBindingSource.EndEdit();
    this.tableAdapterManager.UpdateAll(this.database1DataSet);
    //And here is where I show Form3
    private void projetoDataGridView_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
    Cadastro.ShowDialog();
    //And here is where I show Form2
    private void funcaoDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    Config.ShowDialog();
    }// And the code keeps on going}
    And this is a snippet from Form3:
    public partial class Form3 : Form
    public Form3()
    InitializeComponent();
    private void Form3_Load(object sender, EventArgs e)
    this.projetoTableAdapter.Fill(this.database1DataSet.Projeto);
    this.modulosTableAdapter.Fill(this.database1DataSet.Modulos);
    private void btnOK_Click(object sender, EventArgs e)
    if (projetoTextBox.Text == "")
    MessageBox.Show("some text here");
    else
    ////// HERE IS THE PLACE WHERE I WANT TO CALL THE METHOD! "salva_banco()"
    I've read lots of suggestions but none satisfied my condition.
    I appreciate any help.
    Thanks.

    You need to find the instance of the PRINCIPAL form to call the method on.  If you know there will always be exactly one open you can use:
    var principalForm = Application.OpenForms.OfType<PRINCIPAL>().Single();
    principalForm.salva_banco();
    David
    David http://blogs.msdn.com/b/dbrowne/

  • Back button not working after navigation using method navigate_to_account

    Hi,
    I have the following scenario.
    1. From Account Search navigating to one Account (Page 1 to Page 2)
    2. From Account there is a hyperlink with opens another page (Page 2 to Page 3). For this navigation I am using method  cl_crm_uiu_bp_tools=>navigate_to_account
    3. Page is opening successfully but when I am clicking on the BACK button for the first, nothing is happening. On the second click in the BACK button its navigating back to the Search page. (Page 3 to Page 1).
    So the history is not triggering for Account page (Page 2)
    Please help me with this issue.

    Hi Tapas,
    You actually need to explicitly record it using the below statement.
    RAISE EVENT history_trigger .
    Use this starement before calling the outbound plug.
    Please let me know if you still have any issues.
    Regards,
    Jotsaroop Singh

  • ALV subtotals using methods

    Hi
    Please provide me sample code for subtotals using methods.
    The code is
    DATA: ls_sort TYPE lvc_s_sort.
    ls_sort-spos = '1' .
    ls_sort-fieldname = 'BWART'.
    ls_sort-up = 'X'.
    ls_sort-subtot = 'X'.
    *ls_sort-group = 'UL'.
    APPEND ls_sort TO p_gt_sort.
    endform
    but it is not working
    Please help me

    Hi,
    this is how you should do...
    CLASS lcl_event_handler DEFINITION DEFERRED.
    DATA: dg_events_receiver TYPE REF
                                TO lcl_event_handler.  "event receiver
    *       CLASS lcl_event_handler DEFINITION
    *       For Event handling                                             *
    CLASS lcl_event_handler DEFINITION.
      PUBLIC SECTION.
        CLASS-METHODS:
           subtotal_text        FOR EVENT subtotal_text
                             OF cl_gui_alv_grid
                             IMPORTING es_subtottxt_info
                                       ep_subtot_line
                                       e_event_data.
    ENDCLASS.                    "VERIFY_EVENT_HANDLER DEFINITION
    *       CLASS lcl_event_handler IMPLEMENTATION
    *       Implementation of event handler method                        *
    CLASS lcl_event_handler IMPLEMENTATION.
      METHOD subtotal_text.
        PERFORM d0100_event_subtotal_text USING es_subtottxt_info
                                                ep_subtot_line
                                                e_event_data.
      ENDMETHOD.                    "subtotal_text
    ENDCLASS.                    "lcl_event_handler IMPLEMENTATION
    *--set event handler
      PERFORM set_event_handler.
      CALL METHOD dg_grid->set_table_for_first_display
        EXPORTING
          is_layout                     = ds_layout
        CHANGING
          it_outtab                     = <fs_f>
          it_fieldcatalog               = dt_alv_cat
          it_sort                       = dt_sort
        EXCEPTIONS
          invalid_parameter_combination = 1
          program_error                 = 2
          too_many_lines                = 3
          OTHERS                        = 4.
      IF sy-subrc <> 0.
        MESSAGE i000 WITH
             'Error in calling SET_TABLE_FOR_FIRST_DISPLAY'(026).
      ENDIF.
    *&      Form  set_event_handler
    *       event handler
    *  -->  p1        text
    *  <--  p2        text
    FORM set_event_handler .
      CREATE OBJECT dg_events_receiver.
      SET HANDLER dg_events_receiver->subtotal_text
                  FOR dg_grid.
    ENDFORM.                    " set_event_handler
    *&      Form  d0100_event_subtotal_text
    *       To handle subtotal text event
    *      -->P_ES_SUBTOTTXT_INFO  text
    *      -->P_EP_SUBTOT_LINE  text
    *      -->P_E_EVENT_DATA  text
    FORM d0100_event_subtotal_text  USING
                            p_es_subtottxt_info TYPE lvc_s_stxt
                           p_ep_subtot_line TYPE REF TO data
                           p_e_event_data TYPE REF TO cl_alv_event_data .
      FIELD-SYMBOLS: <fs> TYPE ANY.
      ASSIGN p_e_event_data->m_data->* TO <fs>.
      <fs> = 'TOTAL'(027).
    ENDFORM.                    " d0100_event_subtotal_text
    Regards
    vijay

Maybe you are looking for

  • Export in MP3 to SD card

    My car has two slots for SD cards with music. The cards must be formatted in FAT32 with songs in MP3 format. If I create a Playlist with auto tunes, how would I export this in MP3? I figure I can get them on an SD using some sort of reader. I've gone

  • TCP Listener returned error on accept = AFP blows up. Need help

    Environment: 10.6.7 Server. Xserver. All Mac clients. It's a school. Problem: AFP refusing connections or not loading the Home Directory Symptoms: Library/Logs/AppleFileService/AppleFileServiceError.log blown out with "TCP Listener returned error on

  • When I import photos they are changing color, what to do to come back to regular download?

    Lightroom worked good, I tuned it off and I turn on again and all my photos after import are in different color like black with white and gree, all the same tone. What to do to come back to previous? what have I done?

  • Photoshop crashing randomly in OSX

    Hey All, Working with a file in photoshop cs3 and the new MacBook Pro and it has been crashing all day. It crashes randomly, not on open or save, and even with a force quit it only closes the window, not the photoshop program. I have to do a hard reb

  • The wrong apple id shows up in the app store

    I bought a new iphone 4g.  Until yesterday, all was well.  Today the app store is asking for an apple id that is associated with another iphone on our itunes account.   In my settings, my apple id is correct.  I have tried signing into itunes with my