Constructor in ooabap

what is the functionality of the constructor.
what is the diff b/w static and instance constructor.

Hi Krishnaveni,
Static Constructor:
Static constructors are executed the first time you address a class.  In case you address a static attribute declared in a superclass using the class name of a subclass, only the static constructor of the superclass is executed.  There is only one static constructor.
Instance Constructor:
This is the first method which is called when an object is created. There can be a constructor for every instance of an object created.
Regards,
Sai

Similar Messages

  • Error while calling a super class public method in the subclass constructor

    Hi ,
    I have code like this:
    CLASS gacl_applog DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS:
                create_new_a
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXPORTING  pfx_log_hndl TYPE balloghndl
                   EXCEPTIONS error
    ENDCLASS.
    CLASS gacl_applog IMPLEMENTATION.
      METHOD create_new_a.
        DATA: ls_log TYPE bal_s_log.
      Header aufsetzen
        MOVE pf_extnumber TO ls_log-extnumber.
        ls_log-object     = pf_obj.
        ls_log-subobject  = pf_subobj.
        ls_log-aluser     = sy-uname.
        ls_log-alprog     = sy-repid.
        ls_log-aldate     = sy-datum.
        ls_log-altime     = sy-uzeit.
        ls_log-aldate_del = ls_log-aldate + 1.
        CALL FUNCTION 'BAL_LOG_CREATE'
             EXPORTING
                  i_s_log      = ls_log
             IMPORTING
                  e_log_handle = pfx_log_hndl
             EXCEPTIONS
                  OTHERS       = 1.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID      sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH    sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    CLASS gcl_applog_temp DEFINITION INHERITING FROM gacl_applog.
      PUBLIC SECTION.
        DATA: log_hndl   TYPE balloghndl READ-ONLY
            , t_log_hndl TYPE bal_t_logh READ-ONLY
        METHODS: constructor
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXCEPTIONS error
               , msg_add      REDEFINITION
               , display      REDEFINITION
    ENDCLASS.
    CLASS gcl_applog_temp IMPLEMENTATION.
      METHOD constructor.
        CALL METHOD create_new_a
               EXPORTING  pf_obj       = pf_obj
                          pf_subobj    = pf_subobj
                          pf_extnumber = pf_extnumber
               IMPORTING  pfx_log_hndl = log_hndl.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    A public method of Super class has been called from the constructor of the sub class. we are getting the syntax error :
    ' In the constructor method, you can only access instance attributes, instance methods, or "ME" after calling the constructor of the superclass…'
    Can you please suggest how to change the code with out affecting the functioanlity.
    Thank you ,
    Lakshmi.

    Hi,
    Call that method by instance of Subclass.   OR
    SUPER-->method.
    Read very useful document
    Constructors
    Constructors are special methods that cannot be called using CALL METHOD. Instead, they are called automatically by the system to set the starting state of a new object or class. There are two types of constructors - instance constructors and static constructors. Constructors are methods with a predefined name. To use them, you must declare them explicitly in the class.
    The instance constructor of a class is the predefined instance method CONSTRUCTOR. You declare it in the public section as follows:
    METHODS CONSTRUCTOR
            IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL]..
            EXCEPTIONS.. <ei>.
    and implement it in the implementation section like any other method. The system calls the instance constructor once for each instance of the class, directly after the object has been created in the CREATE OBJECT statement. You can pass the input parameters of the instance constructor and handle its exceptions using the EXPORTING and EXCEPTIONS additions in the CREATE OBJECT statement.
    The static constructor of a class is the predefined static method CLASS_CONSTRUCTOR. You declare it in the public section as follows:
    CLASS-METHODS CLASS_CONSTRUCTOR.
    and implement it in the implementation section like any other method. The static constructor has no parameters. The system calls the static constructor once for each class, before the class is accessed for the first time. The static constructor cannot therefore access the components of its own class.
    Pls. reward if useful....

  • Value  set in constructor is not getting saved in button  Action method

    Hi All,
    I am not understanding why the value set ( On Condition )in constructor is not hold in the button actoin method.
    Could any body explain me on that
    for this I will try to explain with sample example
    I have taken a button and add a integer property in session bean.
    now if session bean's property is even then I am trying to set the button value to bidNow other wise Accept Invitation.
    Till this opstion everything is OK
    but once I click on Button,
    Constructor is doing the right job only. But I do not understand why in button action I am getting the First Value only.
    public Page1() {
            // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Initialization">
            try {
                if (getSessionBean1().getIntValue()%2==0)
                    button1.setValue("BidNow");
                else
                    button1.setValue("Accept Invitation");
                getSessionBean1().setIntValue(getSessionBean1().getIntValue()+1);
                log("In Constructor Button Value : "+button1.getValue());
            } catch (Exception e) {
                log("Page1 Initialization Failure", e);
                throw e instanceof javax.faces.FacesException ? (FacesException) e: new FacesException(e);
            // </editor-fold>
            // Additional user provided initialization code
        public String button1_action() {
            // TODO Replace with your code
            log("In Action Button Value : "+button1.getValue());
            return null;
        }and here is the log
    [#|2005-07-19T11:55:17.859+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:17.859+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:18.359+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:18.359+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:18.843+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:18.843+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:19.312+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:19.312+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:19.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:19.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:20.234+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:20.250+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:20.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:20.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:21.328+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:21.328+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:35.437+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:35.437+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:35.906+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:35.921+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:36.265+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:36.265+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:36.890+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:36.890+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:37.171+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:37.171+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:37.468+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:37.468+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]As per this log every time I am getting Bid Now only in action, though the value is changed in Construtcor
    Can u explain the reason for this

    Hi Sudhakar,
    Please try the following and you will get an idea as to what is happening:
    1. Drag and drop a button, 2 outputText components
    2. Add a property to the session bean called intValue of type int. Customize it to set it's initial value to 0
    3. Add the following lines of code to the constructor
    outputText1.setValue("" + getSessionBean1().getIntValue());
    getSessionBean1().setIntValue(getSessionBean1().getIntValue()+1);
    4. Double click on the button component to go to the button action method.
    5. Add the following line of code
    outputText2.setValue("" + etSessionBean1().getIntValue());
    6. Save and run the application
    7. Watch the values of outputText1 and outputText2 with each click of the button
    Also, try the application with the following code block in the button action method:
    if(getSessionBean1().getIntValue()%2==0){
    button1.setValue("Bid Now");
    } else{
    button1.setValue("Accept Invitation");
    getSessionBean1().setIntValue(getSessionBean1().getIntValue()+1);
    outputText1.setValue(button1.getValue());
    outputText2.setValue("" + getSessionBean1().getIntValue());
    When the above code block is in the button action method the values set to button are as expected.
    Hope that helps
    Cheers
    Giri :-)

  • Passing arraylist between constructors?

    Hi guys,
    I've pretty new to java, and I think i'm having a little trouble
    understanding scope. The program I'm working on is building a jtree
    from an xml file, to do this an arraylist (xmlText) is being built and
    declared in the function Main. It's then called to an overloaded
    constructor which processes the XML into a jtree:
    public Editor( String title, ArrayList xmlText ) throws
    ParserConfigurationException
    Later, in the second constructor which builds my GUI, I try and call
    the same arraylist so I can parse this XML into a set of combo boxes,
    but get an error thrown up at me that i'm having a hard time solving- :
    public Editor( String title ) throws ParserConfigurationException
    // additional code
    // Create a read-only combobox- where I get an error.
    String [] items = (String []) xmlText.toArray (new String[
    xmlText.size () ]);
    JComboBox queryBox = new JComboBox(items);
    JComboBox queryBox2 = new JComboBox(items);
    JComboBox queryBox3 = new JComboBox(items);
    JComboBox queryBox4 = new JComboBox(items);
    JComboBox queryBox5 = new JComboBox(items);
    This is the way I understand the Arraylist can be converted to a string
    to use in the combo boxs. However I get an error thrown up at me here
    at about line 206, which as far as I understand, is because when the
    overloaded constructor calls the other constructor:
    public Editor( String title ) throws ParserConfigurationException -
    It does not pass in the variable xmlText.
    I'm told that the compiler complains because xmlText is not defined
    at that point:
    - it is not a global variable or class member
    - it has not been passed into the function
    and
    - it has not been declared inside the current function
    Can anyone think of a solution to this problem? As I say a lot of this
    stuff is still fairly beyond me, I understand the principles behind the
    language and the problem, but the solution has been evading me so far.
    If anyone could give me any help or a solution here I'd be very
    grateful- I'm getting totally stressed over this.
    The code I'm working on is below, I've highlighted where the error
    crops up too- it's about line 200-206 area. Sorry for the length, I was
    unsure as to how much of the code I should post.
    public class Editor extends JFrame implements ActionListener
    // This is the XMLTree object which displays the XML in a JTree
    private XMLTree XMLTree;
    private JTextArea textArea, textArea2, textArea3;
    // One JScrollPane is the container for the JTree, the other is for
    the textArea
    private JScrollPane jScroll, jScrollRt, jScrollUp,
    jScrollBelow;
    private JSplitPane splitPane, splitPane2;
    private JPanel panel;
    // This JButton handles the tree Refresh feature
    private JButton refreshButton;
    // This Listener allows the frame's close button to work properly
    private WindowListener winClosing;
    private JSplitPane splitpane3;
    // Menu Objects
    private JMenuBar menuBar;
    private JMenu fileMenu;
    private JMenuItem newItem, openItem, saveItem,
    exitItem;
    // This JDialog object will be used to allow the user to cancel an exit
    command
    private JDialog verifyDialog;
    // These JLabel objects will be used to display the error messages
    private JLabel question;
    // These JButtons are used with the verifyDialog object
    private JButton okButton, cancelButton;
    private JComboBox testBox;
    // These two constants set the width and height of the frame
    private static final int FRAME_WIDTH = 600;
    private static final int FRAME_HEIGHT = 450;
    * This constructor passes the graphical construction off to the
    overloaded constructor
    * and then handles the processing of the XML text
    public Editor( String title, ArrayList xmlText ) throws
    ParserConfigurationException
    this( title );
    textArea.setText( ( String )xmlText.get( 0 ) + "\n" );
    for ( int i = 1; i < xmlText.size(); i++ )
    textArea.append( ( String )xmlText.get( i ) + "\n" );
    try
    XMLTree.refresh( textArea.getText() );
    catch( Exception ex )
    String message = ex.getMessage();
    System.out.println( message );
    }//end try/catch
    } //end Editor( String title, String xml )
    * This constructor builds a frame containing a JSplitPane, which in
    turn contains two
    JScrollPanes.
    * One of the panes contains an XMLTree object and the other contains
    a JTextArea object.
    public Editor( String title ) throws ParserConfigurationException
    // This builds the JFrame portion of the object
    super( title );
    Toolkit toolkit;
    Dimension dim, minimumSize;
    int screenHeight, screenWidth;
    // Initialize basic layout properties
    setBackground( Color.lightGray );
    getContentPane().setLayout( new BorderLayout() );
    // Set the frame's display to be WIDTH x HEIGHT in the middle of
    the screen
    toolkit = Toolkit.getDefaultToolkit();
    dim = toolkit.getScreenSize();
    screenHeight = dim.height;
    screenWidth = dim.width;
    setBounds( (screenWidth-FRAME_WIDTH)/2,
    (screenHeight-FRAME_HEIGHT)/2, FRAME_WIDTH,
    FRAME_HEIGHT );
    // Build the Menu
    // Build the verify dialog
    // Set the Default Close Operation
    // Create the refresh button object
    // Add the button to the frame
    // Create two JScrollPane objects
    jScroll = new JScrollPane();
    jScrollRt = new JScrollPane();
    // First, create the JTextArea:
    // Create the JTextArea and add it to the right hand JScroll
    textArea = new JTextArea( 200,150 );
    jScrollRt.getViewport().add( textArea );
    // Next, create the XMLTree
    XMLTree = new XMLTree();
    XMLTree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.SINGLE_TREE_SELECTION
    XMLTree.setShowsRootHandles( true );
    // A more advanced version of this tool would allow the JTree to
    be editable
    XMLTree.setEditable( false );
    // Wrap the JTree in a JScroll so that we can scroll it in the
    JSplitPane.
    jScroll.getViewport().add( XMLTree );
    // Create the JSplitPane and add the two JScroll objects
    splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, jScroll,
    jScrollRt );
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(200);
    jScrollUp = new JScrollPane();
    jScrollBelow=new JScrollPane();
    // Here is were the error is coming up
    String [] items = (String []) xmlText.toArray (new String[
    xmlText.size () ]);
    JComboBox queryBox = new JComboBox(items);
    JComboBox queryBox2 = new JComboBox(items);
    JComboBox queryBox3 = new JComboBox(items);
    JComboBox queryBox4 = new JComboBox(items);
    JComboBox queryBox5 = new JComboBox(items);
    * I'm adding the scroll pane to the split pane,
    * a panel to the top of the split pane, and some uneditible
    combo boxes
    * to them. Then I'll rearrange them to rearrange them, but
    unfortunately am getting an error thrown up above.
    panel = new JPanel();
    panel.add(queryBox);
    panel.add(queryBox2);
    panel.add(queryBox3);
    panel.add(queryBox4);
    panel.add(queryBox5);
    jScrollUp.getViewport().add( panel );
    // Now building a text area
    textArea3 = new JTextArea(200, 150);
    jScrollBelow.getViewport().add( textArea3 );
    splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
    jScrollUp, jScrollBelow);
    splitPane2.setPreferredSize( new Dimension(300, 200) );
    splitPane2.setDividerLocation(100);
    splitPane2.setOneTouchExpandable(true);
    // in here can change the contents of the split pane
    getContentPane().add(splitPane2,BorderLayout.SOUTH);
    // Provide minimum sizes for the two components in the split pane
    minimumSize = new Dimension(200, 150);
    jScroll.setMinimumSize( minimumSize );
    jScrollRt.setMinimumSize( minimumSize );
    // Provide a preferred size for the split pane
    splitPane.setPreferredSize( new Dimension(400, 300) );
    // Add the split pane to the frame
    getContentPane().add( splitPane, BorderLayout.CENTER );
    //Put the final touches to the JFrame object
    validate();
    setVisible(true);
    // Add a WindowListener so that we can close the window
    winClosing = new WindowAdapter()
    public void windowClosing(WindowEvent e)
    verifyDialog.show();
    addWindowListener(winClosing);
    } //end Editor()
    * When a user event occurs, this method is called. If the action
    performed was a click
    * of the "Refresh" button, then the XMLTree object is updated using
    the current XML text
    * contained in the JTextArea
    public void actionPerformed( ActionEvent ae )
    if ( ae.getActionCommand().equals( "Refresh" ) )
    try
    XMLTree.refresh( textArea.getText() );
    catch( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    else if ( ae.getActionCommand().equals( "OK" ) )
    exit();
    else if ( ae.getActionCommand().equals( "Cancel" ) )
    verifyDialog.hide();
    }//end if/else if
    } //end actionPerformed()
    // Program execution begins here. An XML file (*.xml) must be passed
    into the method
    public static void main( String[] args )
    String fileName = "";
    BufferedReader reader;
    String line;
    ArrayList xmlText = null;
    Editor Editor;
    // Build a Document object based on the specified XML file
    try
    if( args.length > 0 )
    fileName = args[0];
    if ( fileName.substring( fileName.indexOf( '.' ) ).equals(
    ".xml" ) )
    reader = new BufferedReader( new FileReader( fileName )
    xmlText = new ArrayList();
    while ( ( line = reader.readLine() ) != null )
    xmlText.add( line );
    } //end while ( ( line = reader.readLine() ) != null )
    // The file will have to be re-read when the Document
    object is parsed
    reader.close();
    // Construct the GUI components and pass a reference to
    the XML root node
    Editor = new Editor( "Editor 1.0", xmlText );
    else
    help();
    } //end if ( fileName.substring( fileName.indexOf( '.' )
    ).equals( ".xml" ) )
    else
    Editor = new Editor( "Editor 1.0" );
    } //end if( args.length > 0 )
    catch( FileNotFoundException fnfEx )
    System.out.println( fileName + " was not found." );
    exit();
    catch( Exception ex )
    ex.printStackTrace();
    exit();
    }// end try/catch
    }// end main()
    // A common source of operating instructions
    private static void help()
    System.out.println( "\nUsage: java Editor filename.xml" );
    System.exit(0);
    } //end help()
    // A common point of exit
    public static void exit()
    System.out.println( "\nThank you for using Editor 1.0" );
    System.exit(0);
    } //end exit()
    class newMenuHandler implements ActionListener
    public void actionPerformed( ActionEvent ae )
    textArea.setText( "" );
    try
    // Next, create a new XMLTree
    XMLTree = new XMLTree();
    XMLTree.getSelectionModel().setSelectionMode(
    TreeSelectionModel.SINGLE_TREE_SELECTION );
    XMLTree.setShowsRootHandles( true );
    // A more advanced version of this tool would allow the JTree
    to be editable
    XMLTree.setEditable( false );
    catch( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    }//end actionPerformed()
    }//end class newMenuHandler
    class openMenuHandler implements ActionListener
    JFileChooser jfc;
    Container parent;
    int choice;
    openMenuHandler()
    super();
    jfc = new JFileChooser();
    jfc.setSize( 400,300 );
    jfc.setFileFilter( new XmlFileFilter() );
    parent = openItem.getParent();
    }//end openMenuHandler()
    public void actionPerformed( ActionEvent ae )
    // Displays the jfc and sets the dialog to 'open'
    choice = jfc.showOpenDialog( parent );
    if ( choice == JFileChooser.APPROVE_OPTION )
    String fileName, line;
    BufferedReader reader;
    fileName = jfc.getSelectedFile().getAbsolutePath();
    try
    reader = new BufferedReader( new FileReader( fileName ) );
    textArea.setText( reader.readLine() + "\n" );
    while ( ( line = reader.readLine() ) != null )
    textArea.append( line + "\n" );
    } //end while ( ( line = reader.readLine() ) != null )
    // The file will have to be re-read when the Document
    object is parsed
    reader.close();
    XMLTree.refresh( textArea.getText() );
    catch ( Exception ex )
    String message = ex.getMessage();
    ex.printStackTrace();
    }//end try/catch
    jfc.setCurrentDirectory( new File( fileName ) );
    } //end if ( choice == JFileChooser.APPROVE_OPTION )
    }//end actionPerformed()
    }//end class openMenuHandler
    class saveMenuHandler implements ActionListener
    JFileChooser jfc;
    Container parent;
    int choice;
    saveMenuHandler()
    super();
    jfc = new JFileChooser();
    jfc.setSize( 400,300 );
    jfc.setFileFilter( new XmlFileFilter() );
    parent = saveItem.getParent();
    }//end saveMenuHandler()
    public void actionPerformed( ActionEvent ae )
    // Displays the jfc and sets the dialog to 'save'
    choice = jfc.showSaveDialog( parent );
    if ( choice == JFileChooser.APPROVE_OPTION )
    String fileName;
    File fObj;
    FileWriter writer;
    fileName = jfc.getSelectedFile().getAbsolutePath();
    try
    writer = new FileWriter( fileName );
    textArea.write( writer );
    // The file will have to be re-read when the Document
    object is parsed
    writer.close();
    catch ( IOException ioe )
    ioe.printStackTrace();
    }//end try/catch
    jfc.setCurrentDirectory( new File( fileName ) );
    } //end if ( choice == JFileChooser.APPROVE_OPTION )
    }//end actionPerformed()
    }//end class saveMenuHandler
    class exitMenuHandler implements ActionListener
    public void actionPerformed( ActionEvent ae )
    verifyDialog.show();
    }//end actionPerformed()
    }//end class exitMenuHandler
    class XmlFileFilter extends javax.swing.filechooser.FileFilter
    public boolean accept( File fobj )
    if ( fobj.isDirectory() )
    return true;
    else
    return fobj.getName().endsWith( ".xml" );
    }//end accept()
    public String getDescription()
    return "*.xml";
    }//end getDescription()
    }//end class XmlFileFilter
    } //end class Editor
    Sorry if this post has been a bit lengthy, any help you guys could give
    me solving this would be really appreciated.
    Thanks,
    Iain.

    Hey. Couple pointers:
    When posting, try to keep code inbetween code tags (button between spell check and quote original). It will pretty-print the code.
    Posting code is good. Usually, though, you want to post theminimum amount of code which runs and shows your problem.
    That way people don't have to wade through irrelevant stuff and
    they have an easier time helping.
    http://homepage1.nifty.com/algafield/sscce.html
    As for your problem, this is a scope issue. You declare an
    ArrayList xmlText in main(). That means that everywhere after
    the declaration in main(), you can reference your xmlText.
    So far so good. Then, inside main(), you call
    Editor = new Editor( "Editor 1.0", xmlText );Now you've passed the xmlText variable to a new method,
    Editor(String title, ArrayList xmlText) [which happens to be a
    constructor, but that's not important]. When you do that, you
    make the two variables title and xmlText available to the whole
    Editor(String, ArrayList) method.
    This is where you get messed up. You invoke another method
    from inside Editor(String, ArrayList). When you call
    this(title);you're invoking the method Editor(String title). You aren't passing
    in your arraylist, though. You've got code in the Editor(String) method
    which is trying to reference xmlText, but you'd need to pass in
    your ArrayList in order to do so.
    My suggestion would be to merge the two constructor methods into
    one, Editor(String title, ArrayList xmlText).

  • Code in main does not require catch, but code in constructor does

    this is the original program, its all in main. i took all the code out of main and put it in a constructor to make it more usable, and started making the necessary adjustments. i eventually got it to work but i had to catch exceptions EVERYWHERE. why does this code not require so many exceptions when the code is in main?
    import java.io.BufferedInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    public class MainClass {
      public static void main(String args[]) throws Exception {
        URL u = new URL("");
        URLConnection uc = u.openConnection();
        String contentType = uc.getContentType();
        int contentLength = uc.getContentLength();
         // ||
        if (contentLength == -1) {
          throw new IOException("Error: No File Found.");
        InputStream raw = uc.getInputStream();
        InputStream in = new BufferedInputStream(raw);
        byte[] data = new byte[contentLength];
        int bytesRead = 0;
        int offset = 0;
        while (offset < contentLength) {
          bytesRead = in.read(data, offset, data.length - offset);
          if (bytesRead == -1)
            break;
          offset += bytesRead;
        in.close();
        if (offset != contentLength) {
          throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
         String dirText = "text";
         String dirTarget = "target";
         String filename = u.getFile().substring(u.getFile().lastIndexOf('/') + 1);
         String dirAndFile;
         // determine weather the file is a target or is to be parsed for more files
         if(contentType.startsWith("text/")) {
              dirAndFile = dirText + "\\" + filename;
         else {
              dirAndFile = dirTarget + "\\" + filename;
        FileOutputStream out = new FileOutputStream(dirAndFile);
        out.write(data);
        out.flush();
        out.close();
    }Edited by: chopficaro on May 1, 2010 8:15 AM

    ok but still, why do i not have to catch all these exceptions when the code is in main rather than a constructor? heres the code after i put it in the constructor:
    import java.io.BufferedInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    import java.net.MalformedURLException;
    public class MainClass {
         public static void main(String args[]) throws Exception
              MainClass mc = new MainClass("http://www.google.com/intl/en_ALL/images/logo.gif");
         MainClass(String addr)
              URL u = null;
              try
                   u = new URL(addr);
              catch (MalformedURLException e)
                   // Print out the exception that occurred
                   System.out.println("Invalid URL "+addr+": "+e.getMessage());
              URLConnection uc = null;
              try
                   uc = u.openConnection();
              catch (IOException e)
                   // Print out the exception that occurred
                   System.out.println("Unable to create "+addr+": "+e.getMessage());
              String contentType = uc.getContentType();
              int contentLength = uc.getContentLength();
              if (contentLength == -1)
                   System.out.println("no file");//throw new IOException("Error: No File Found.");
              InputStream raw=null;
              InputStream in=null;
              try
                   raw = uc.getInputStream();
                   in = new BufferedInputStream(raw);
              catch (IOException e)
              // Print out the exception that occurred
              System.out.println("bad input stream "+e.getMessage());
              byte[] data = new byte[contentLength];
              int bytesRead = 0;
              int offset = 0;
              while (offset < contentLength)
                   try
                        bytesRead = in.read(data, offset, data.length - offset);
                   catch (IOException e)
                        // Print out the exception that occurred
                        System.out.println(e.getMessage());
                   if (bytesRead == -1)
                   break;
                   offset += bytesRead;
              try
                   in.close();
              catch (IOException e)
                   // Print out the exception that occurred
                   System.out.println(e.getMessage());
              if (offset != contentLength)
                   System.out.println("didnt read enough bytes"); //throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
              String dirText = "text";
              String dirTarget = "target";
              try
                   String filename = u.getFile().substring(u.getFile().lastIndexOf('/') + 1);
                   String dirAndFile;
                   // determine weather the file is a target or is to be parsed for more files
                   if(contentType.startsWith("text/"))
                        dirAndFile = dirText + "\\" + filename;
                   else
                        dirAndFile = dirTarget + "\\" + filename;
                   FileOutputStream out = new FileOutputStream(dirAndFile);
                   out.write(data);
                   out.flush();
                   out.close();
              catch (IOException e)
                   // Print out the exception that occurred
                   System.out.println(e.getMessage());
    }

  • Problem with root and constructors

    hello guys,
    i have serious problem, its 2 days i am trying to do something about it,
    i have some object inside object inside another object,
    if in their constructors i write:
    MovieClip(root).someVar
    (or function)
    its not working!
    it works only i regular functions,
    i cant even call a egular function from the constructor,
    please help my guys, i really need this!
    thanks alot!

    function YourDisplayObjectClass(){
    // this is the contructor
    // trying to reference MovieClip(root) or stage will trigger a null ref error
    // because YourDisplayObjectClass instance isn't added to the stage, yet
    this.addEventListener(Event.ADDED_TO_STAGE,init);
    private function init():void{
    // from here you can reference displaylist items.
    trace(MovieClip(root),stage);

  • Having a problem with inheritance and a constructor

    i have two classes, i'm just going to give the constructors anyway. I'm having trouble getting the CDImage constructor to inherit something from songs, I believe the instructions are missing something or the cs lab guy misinterpreted them.
    package songs;
    import java.text.*;
    public class Song implements Comparable {
        private int songLength;
        private String artistName;
        private String songName;
        public Song(int songLength, String artistNames, String songName) {
            this.songLength = songLength;
            this.artistName = artistNames;
            this.songName = songName;
        }These are the instructions that i beleive may be incorrect:
    Design a CDImage class to represent a music CD. The constructor takes three parameters: the title of the CD, the recording label, and the number of tracks on the CD. (Each track contains one song.) The CDImage class uses the Song class developed above and should contain methods to accomplish the following:package songs;
    import java.text.*;
    public class CDImage extends Song {
        private String title;
        private String label;
        private int numberTracks;
        private Song[] songs;
        public CDImage(String title, String label, int tracks){
        this.title = title;// this is the album name
        this.label = label;
        numberTracks = tracks;
        songs = new Song [numberTracks];
        }i know i need to use the super modifier under the constructor but how? because nothing in the constructor of the CDImage class refers directly to the constructor in the Song class
    thanks in advance.
    Message was edited by:
    kevin123

    you know whats funny, this project has to do with arrays of objects and not inheritance. We learned inheritance last week but the lab we are doing which is this, is for arrays of objects. sorry for the confusion lol. so you can completely ignore this, it actually has it in big bold letters at the top of the web page for the lab.

  • Problem with constructors and using public classes

    Hi, I'm totally new to Java and I'm having a lot of problems with my program :(
    I have to create constructor which creates bool's array of adequate size to create a sieve of Eratosthenes (for 2 ->n).
    Then it has to create public method boolean prime(m) which returs true if the given number is prime and false if it's not prime.
    And then I have to create class with main function which chooses from the given arguments the maximum and creates for it the sieve
    (using the class which was created before) and returns if the arguments are prime or not.
    This is what I've written but of course it's messy and it doesn't work. Can anyone help with that?
    //part with a constructor
    public class ESieve {
      ESieve(int n) {
    boolean[] isPrime = new boolean[n+1];
    for (int i=2; i<=n; i++)
    isPrime=true;
    for(int i=2;i*i<n;i++){
    if(isPrime[i]){
    for(int j=i;i*j<=n;j++){
    isPrime[i*j]=false;}}}
    public static boolean Prime(int m)
    for(int i=0; i<=m; i++)
    if (isPrime[i]<2) return false;
    try
    m=Integer.parseInt(args[i]);
    catch (NumberFormatException ex)
    System.out.println(args[i] + " is not an integer");
    continue;
    if (isPrime[i]=true)
    System.out.println (isPrime[i] + " is prime");
    else
    System.out.println (isPrime[i] + " is not prime");
    //main
    public class ESieveTest{
    public static void main (String args[])
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    new ESieve(maximum);
    for(int i=0; i<args.length; i++)
    Prime(i);}

    I've made changes and now my code looks like this:
    public class ESieve {
      ESieve(int n) {
       sieve(n);
    public static boolean sieve(int n)
         boolean[] s = new boolean[n+1];
         for (int i=2; i<=n; i++)
    s=true;
    for(int i=2;i*i<n;i++){
    if(s[i]){
    for(int j=i;i*j<=n;j++){
    s[i*j]=false;}}}
    return s[n];}
    public static boolean prime(int m)
    if (m<2) return false;
    boolean x = sieve(m);
    if (x=true)
    System.out.println (m + " is prime");
    else
    System.out.println (m + " is not prime");
    return x;}
    //main
    public class ESieveTest{
    public static int max(int[] args) {
    int maximum = args[0];
    for (int i=1; i<args.length; i++) {
    if (args[i] > maximum) {
    maximum = args[i];
    return maximum;
    public static void main (String[] args)
    int n; int i, j;
    for(i=0;i<=args.length;i++)
    n=Integer.parseInt(args[i]);
    int maximum=max(args[]);
    ESieve S = new ESieve(maximum);
    for(i=0; i<args.length; i++)
    S.prime(i);}
    It shows an error for main:
    {quote} ESieveTest.java:21: '.class' expected
    int maximum=max(args[]); {quote}
    Any suggestions how to fix it?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Problem with constructor of inner class.

    Hi everybody!
    I have an applet which loads images from a database.
    i want to draw the images in a textarea, so i wrote an inner class, which extends textarea and overrides the paint method.
    but everytime i try to disply the applet in the browser this happens:
    java.lang.NoClassDefFoundError: WohnungSuchenApplet$Malfl�che
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:1590)
    at java.lang.Class.getConstructor0(Class.java:1762)
    at java.lang.Class.newInstance0(Class.java:276)
    at java.lang.Class.newInstance(Class.java:259)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:567)
    at sun.plugin.AppletViewer.createApplet(AppletViewer.java:1778)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:496)
    at sun.applet.AppletPanel.run(AppletPanel.java:293)
    at java.lang.Thread.run(Thread.java:536)
    so my class has no own constructor, it just has the paint method overwritten.
    my class looks like this:
    public class Malfl�che extends javax.swing.JTextArea{
    public void paint(Graphics g){
    Color grey=new Color(220,220,220);
    g.drawImage(img,10,10,null);
    how should a constructor for this class look like?
    sorry i am quite new to this, so i really dont have a clue!
    my class does not have any attributes or requires any so it doesnt need a constructor, doesnt it?
    thanks a lot
    tim

    First off, unlike regular classes, inner classes can be declared public, private, protected, and default.
    Secondly, why are you using the JTextArea to display an image, why not use a JLabel, which takes an Image object as its constructor.
    Thirdly, when you drew your image you did not give it a width and height
    g.drawImage(img, 0,0, img.getWidth(null), img.getHeight(null), null);
    otherwise it will make your image 1 X 1 pixels. not big enough to see.

  • Unable to Create Requestor ABCS using AIA Constructor in Jdev 11.1.1.2

    Hi Gurus,
    I'm currently trying to create ABCS Requester with J developer 11.1.1.2 using the AIA Service Constructor.
    The Composite Application shows the BPEL Component and the target services under the Composite screen.When we click on the BPEL Component we dont the process flow.
    Steps Followed
    1. Create project in Project Lifecycle Workbench
    2.Using the AIA Service Constructor connect to the AIA_LIFECYCLE Workbench.
    3.Select the RequestorABCS Service
    4.Filled out all the ApplicationName,ShortName,Service Version etc on Step 3 of 8
    5. Selected the Service Operation as Query.
    6.Under ABM import the Custom XSD structure and provided the Input and output message
    7.Select the message pattern as request/response
    8.Target Service Step selected the Query Service (this would query the required Customer Content which needs to be mapped).
    9.The the AIA Service Constructor creates BPEL Composite Component.
    When we double and open the BPEL Component we just see the error handling and partner link information.
    We are unable see any assign,scope invoke component on the swim lanes..
    Has anyone experienced this issue while creating ABCS Requester.
    Regards
    Sabir

    Hi Everyone,
    I was able to create Requestor ABCS in Jdev 11.1.1.2 by selecting EBS,wsdl as target. This is workaround you need to follow to create requestor ABCS where you have V2 wsdl available.
    Looks like there is bug#9541128 assigned for this issue. And looks like it would be fixed in 11.1.1.4 version of Jdev as per Oracle Support.
    Regards
    Sabir

  • Difference between constructor & Methods if any ?

    In the below code I use the constructor ConstructorShirt1('M') to pass the value of M to the class ConstructorShirt1, but why do we have to do this, instead can we not just use a method and write the same thing in a method.
    class ConstructorShirt1Test {
         public static void main (String args[]) {
    ConstructorShirt1 constShirt = new ConstructorShirt1('M');
    char colorCode;
              colorCode = constShirt.getColorCode();
    System.out.println("Color Code: " + colorCode);
    class ConstructorShirt1 {
    private int shirtID = 0; // Default ID for the shirt
    private String description = "-description required-"; // default
    // The color codes are R=Red, B=Blue, G=Green, U=Unset
    private char colorCode = 'U';
    private double price = 0.0; // Default price for all items
    private int quantityInStock = 0; // Default quantity for all items
    public ConstructorShirt1(char startingCode) {
    switch (startingCode) {
    case 'R':
    case 'G':
    case 'B':
    colorCode = startingCode;
    break;
    default:
    System.out.println("Invalid colorCode. Use R, G, or B");
    public char getColorCode() {
    return colorCode;
    } // end of class
    So I am not clear what is the difference between constructor and methods if any ? or if not when to use a constructor and when to use a method.
    I would be glad if somebody throws light on this topic.
    PK

    There shouldn't be any confusion on this one... a constructor is meant to create an instance of the class. It can also set the state of its member variables in the process, like the constructor you are using. The same can also be done by a method.
    Wouldn't make much of a difference for simple programs, but this is more pertinent when it comes to designing classes. Like if the developer using the class needs to know what all states he has to set before he needs to do anything useful, then it is better to provide a constructor with some arguments for doing that.

  • Can I have 2 diferent Constructor names in a single class?

    class Test{
    double x;
    double y;
    Test( double a, double b)
    x=a;
    y=b;
    //Can i hv another constructor name with is not test but other name? //Example
    exam(double c, double d)
    x=c;
    y=d;
    }

    If you want different behavior for essentially the "same" constructor signature, use an additional variable to differentiate the signatures. For example:
    Test(double a, double b) { this(a, b, false); }
    Test(double a, double b, boolean exam) {
        if (exam) {
            // exam behavior
        } else {
            // normal Test behavior
    }

  • Help: Factory Class using Inner Class and Private Constructor?

    The situation is as follows:
    I want a GamesCollection class that instantiates Game objects by looking up the information needed from a database. I would like to use Game outside of GamesCollection, but only have it instantiated by GamesCollection to ensure the game actually exist. Each Game object is linked to a database record. If a Game object exist, it must also exist in the database. Game objects can never be removed from the database.
    I thought about making the Game object an inner class of GamesCollection, but this means that Game class constructor is still visible outside. So what if I made Game constructor private? Well, now I can't create Game objects without a static method inside Game class (static Object factory).
    Basically what I need is a constructor for the inner Game class accessible to GamesCollection, but not to the rest of the world (including packages). Is there a way to do this?

    leesiulung wrote:
    As a second look, I was initially confused about your first implementation, but it now makes more sense.
    Let me make sure I understand this:
    - the interface is needed to make the class accessible outside the outer classBetter: it is necessary to have a type that is accessible outside of GameCollection -- what else could be the return type of instance?
    - the instance() method is the object factory
    - the private modifier for the inner class is to prevent outside classes to instantiate this objectRight.
    However, is a private inner class accessible in the outer class? Try it and see.
    How does this affect private/public modifiers on inner classes?Take about five minutes and write a few tests. That should answer any questions you may have.
    How do instantiate a GameImpl object? This basically goes back to the first question.Filling out the initial solution:
    public interface Game {
        String method();
    public class GameCollection {
        private static  class GameImpl implements Game {
            public String method() {
                return "GameImpl";
        public Game instance() {
            return new GameImpl();
        public static void main(String[] args) {
            GameCollection app = new GameCollection();
            Game game = app.instance();
            System.out.println(game.method());
    }Even if you were not interested in controlling game creation, defining interfaces for key concepts like Game is always going to be a good idea. Consider how you will write testing code, for example. How will you mock Game?

  • Print a line after each constructor

    Would one of you java gods tell me how i can print a line after each constructor that tells me that the constructor has been constructed?
    * Employee.java
    * Created on April 28, 2007, 11:58 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author Pete Berardi
    package edu.ctu.peteberardi.phase3db;
    import java.util.Scanner;
    public abstract class Employee extends Object
        protected String EmpName;
        protected String EmpAddress;
        protected String EmpSsn;
        protected String EmpEmployeeID;
        protected double EmpYearlySalary;
        protected double computePay;
        protected String Constructor;
        /** Creates a new instance of Employee */
        public Employee(String name, String address, String ssn,
                String id, double salary, double pay, String cvariable)
          name = EmpName;
          address = EmpAddress;
          ssn = EmpSsn;
          id = EmpEmployeeID;
          salary = EmpYearlySalary;
          pay = computePay;
        public void setEmpName(String name)
            EmpName = name;
        public String getEmpName()
            return EmpName;
        public void setEmpAdress(String address)
            EmpAddress = address;
        public String getEmpAddress()
            return EmpAddress;
        public void setEmpSsn(String ssn)
             EmpSsn = ssn; 
        public String getEmpSsn()
            return EmpSsn;
        public void setEmpID(String id)
            EmpEmployeeID = id;
        public String getEmployeeID()
            return EmpEmployeeID;
        public void setEmpYearlySalary(double salary)
            EmpYearlySalary = salary;
        public double getEmpYearlySalary()
            return EmpYearlySalary;
        public void setcomputePay(double pay)
            computePay = pay;
        public double computePay()
            return computePay;
          public void setContstructor(String cvariable)
             Constructor = cvariable;
        public String Constructor()
            return Constructor;
       public static void main( String args[])
          System.out.print("Constructor has been constructed");
     

    I do not know why you have declared the class as abstract. Abstract class must contain at least one abstract method.
    In your code, there is no abstract method.
    public Employee(String name, String address, String ssn,
                String id, double salary, double pay, String cvariable)
          name = EmpName;
          address = EmpAddress;
          ssn = EmpSsn;
          id = EmpEmployeeID;
          salary = EmpYearlySalary;
          pay = computePay;
          System.out.println("Constructor created");
         }The above code works only when you instantiate the object for the class. If it is abstract class, it will not work.
    Abstract class cannot be instantiated.

  • How can I use multiple constructor

    Hi,
    I have some problem to using multiple constructor in java. It shows some error while compiling the following program. can any one give better solution for me.......
    public class Test6{
       public Test6(){
    this(4);    /*
    C:\Test6.java:5: cannot find symbol
    symbol  : constructor Test6(int)
    location: class Test6
    this(4);
      Test6(byte var){
    System.out.println(var);
    public static void main(String[] args){
    Test6 t6 = new Test6();
    }

    A number like 4 is an integer literal. So, you are passing an int to a function that is defined to accept a byte, hence you have a type mismatch. You need to cast the integer literal to a byte before passing it to the function:
    this( (byte) 4);

Maybe you are looking for