Create Objects Question

Hi. Just curios.
Lets say I have a class called MyClass. In that class I have an method called myMethod()
I then create an Object of that with.
MyClass mc = new MyClass();
mc.myMethod(); Is that better then to do
new MyClass().myMethod()What I think is the difference.
1 with the first example I create an Object that stays "alive"
2 in the second example the Object dies when myMethod() is complete.
Have I understood this correctly ?

MagnusT76 wrote:
Hi. Just curios.
Lets say I have a class called MyClass. In that class I have an method called myMethod()
I then create an Object of that with.
MyClass mc = new MyClass();
mc.myMethod(); Is that better then to do
new MyClass().myMethod()
Neither one is inherently better. If you need to use the object other than for that one method call, you have no choice but to go with the first option. If that's all you need the object for, and the class name and method name and signature are short enough for it to be readable, you might prefer the second one.
What I think is the difference.
1 with the first example I create an Object that stays "alive"
2 in the second example the Object dies when myMethod() is complete.Java doesn't really have a concept of objects being "alive."
In the first case, you are retaining a reference to the object, and as long as you have that reference, it cannot be garbage collected.
In the second case you are not directly retaining a reference to the object, but that doesn't mean that one didn't escape from the method. So the object may or may not be GC-eligible.
public void myMethod() {
  someList.add(this);
}If myMethod() does something like that, then the object is not eligible for GC after your call, even though you didn't explicitly retain a reference, because the list now has a reference to it.

Similar Messages

  • Runtime error 429, activeX component cant create object while using netbet pro on windows 7 & 8.1 HELP!!!

    runtime error 429, activeX component cant create object while using netbet pro
    does anyone know what I could do to fix this problem??? netbet pro was't available for a while then it's back but has yet to run

    What's netbet pro?
    I'd recommend asking questions about third party applications in the vendor's forum, not a Microsoft forum meant for admin scripting.
    EDIT: Ah, some gambling website...
    Don't retire TechNet! -
    (Don't give up yet - 12,950+ strong and growing)

  • ABAP OO:  Duplication of selected data in created objects?

    I am new to ABAP OO and I have a conceptual question/concern that I cannot resolve.  Can someone explain what I am missing?
    I would think that selecting and storing (in internal tables) a large amount of data from many related database tables and, at the same time, creating and storing objects from this same data would unnecessarily consume a huge amount of memory.  To avoid this problem, it seems that the selected data and created objects should not be stored in internal tables simultaneously.
    Does this concern make sense?  If so, how is this problem best handled?
    Does it make sense to delete the corresponding data once the objects are created (to free memory)?
    Or does it make sense to keep the data and only temporarily create objects as needed?
    Thanks.

    Hello Matt
    The approach you describe is to select data first and the feed the object instances with them. <b>Why not let the object instances do the data selection themselves?</b>
    I will give you an example what I mean.
    (1) Lets assume I want to write an application that allows to deal with cost center hierarchies. On the selection screen you can choose one or many cost center hierarchies.
    (2) Using the selection criteria I would select all cost center hierarchies but without any details (just the key values).
    (3) Next I would loop over the cost center hierarchies and create a cost center hierarchy instance (a class you have to define yourself) for each key value. The CONSTRUCTOR of this class will have an IMPORTING parameter like <i>id_kostl_hier</i>.
    (4) In the CONSTRUCTOR method I first check if the cost center hierarchy exists (if not raise an exception-class based exception) and then do the selection of the hierarchy details (e.g. the cost centers).
    (5) The instances are collected in an itab of the "frame" application.
    Using this approach you will have little duplication of data within your application. Furthermore, if you really have to deal with huge amounts of data then you could read them only on demand (like in tree controls where the sub-nodes usually are read when the parent node is expanded).
    Hope I could give you some fresh insights into this exciting topic.
    Regards
      Uwe

  • ABAP OBJECTS: Dynamic Create object

    Hi folks!
    I have a problem... I need to create a dynamic type object with:
    <b>DATA: my_instance TYPE REF TO class1.
    CREATE OBJECT my_instance TYPE (class2).</b>
    <i>* where class1 is a superclass of class2.</i>
    When I do:
    <b>my_instance ?= m_parent.</b>
    <i>* where m_parent is an instance of class1</i>
    My problem is when I want to access to an attribute of the class2, the compiler says that it cannot find the attribute <i>(this is OK, because the attribute is only in the class2).</i>
    My question:
    Is there anyway to access to an atribute of second class when is not in the first class? (i don't want to create the attribute as an attribute of the first class).
    Thanx!!!!

    Hi David,
    When you do the debugging, you are dealing with run-time - i.e., the program is now running and you are just interrupting it at each statement to examine the program state. You will reach the point where the object is already created. That is why you can see all those attributes. But when you comiple, the program is not yet <i>running</i>, so the attributes will be unknown because of the dynamic type specification.
    I think you will have to redesign the program logic. As i had already said in my earlier post, it is not proper to have the attributes specified statically while the class itself is specified dynamically.
    Your situation is somewhat similar to -
    DATA ITAB TYPE TABLE OF SPFLI.
    PERFORM TEST TABLES ITAB.
    FORM TEST TABLES ITAB.
      LOOP AT ITAB.
        WRITE: / ITAB-CARRID.
      ENDLOOP.
    ENDFORM.
    Hope the point is clear.
    Regards,
    Anand Mandalika.

  • Uable to create object in z namespace

    Hi,
    i am having problem in creating an object in Z or Y namespace.
    when i try to create an object it shows an error in creating object saying that system setiings do not allow to make changes to object 'zabc' .
    my  Question is  how to change settings of z namespace to modifiable or is there any other things to set
    thank you
    sai

    Hi,
    Check your settings in the SE06 is set to modifiable.
    Also check your client settings whether it is modifiable or not.
    Regards,
    Vamshi.

  • Creating objects and efficiency

    I am implementing bounding circles for my game and I have a question. I have heard that creating a new object takes up a lot of time (i.e doing it every update). Should I give each of my objects a BoundingSphere instance variable (I created my own simple BoundingSphere class), update it's position every update along with the sprite, or should I remove the instance variable and just return a new BoundingSphere when it is requested?
    Just to clarify:
    Implementation 1:
    private BoundingSphere s;
    public BoundingSphere getBoundingSphere() {
       return s;
    //update s each time sprite is updatedImplementation 2:
    //no private instance variable
    public BoundingSphere getBoundingSphere() {
       return new BoundingSphere(radius, x, y);

    If you know a maximum bound on how many of the created objects you'll need at any given time, you can prevent lots of object creation by implementing an object pool. The pool keeps a list of pre-constructed objects, and to use it, a method may request an object, use a method to initialize its values (not a constructor), then release it back to the pool when it is done using it. This is usually done with Threads to limit the number of them running, but it can be done with any object.
    I hope this helps
    -JBoeing

  • Create object in runtime phase

    Hi all,
    i would create a data grid and pass it an array...
    for example th array looks like this:
    <mx:Array id="planets">
    <mx:Object planet="Mercury" kind="Terrestrial"
    year_duration="0.24" moons="0" cost="1250" />
    <mx:Object planet="Venus" kind="Terrestrial"
    year_duration="0.62" moons="0" cost="2400" />
    <mx:Object planet="Jupiter" kind="Gas giant"
    year_duration="11.86" moons="63" cost="500" />
    <mx:Object planet="Eris" kind="Ice dwarf"
    year_duration="557" moons="1" cost="3000" />
    </mx:Array>
    and datagrid takes dataprovider property equal to "planets".
    ok it'all ok but how can i create an object with those
    properties (planet, kind,...) and values dinamically?
    for example i would create a method that returns a value and
    inserts it in a properties in the object array
    <mx:Object planet = method1() kind = method2() />
    maybe i have to create MyClass that extends Objects...infact
    i see that the dataprovider propertiy is an OBject class...i dont't
    know...
    i appreciate any help..thanks a lot

    Thanks for the reply...
    an other question
    i'have an xml file like this:
    > <root>
    > <week id="1">
    > <production day="monday">
    > <book>23</book>
    > <cds>49</cds>
    > </production>
    > <production day="tuesday">
    > <book>56</book>
    > <cds>68</cds>
    > </production>
    > ...other weeks production...
    > </week>
    > </root>
    i would create objects for every products: book and cds
    for example for book
    <mx:Object monday="23" tuesday="56" />
    and for cds
    <mx:Object monday="56" tuesday="68" />
    can you suggest a procedure to rich this result?
    thanks in advance
    Regards
    Bilbo

  • ABAP Objects Questions

    Hello Everyone,
    I hope someone could answer the following questions:
    Please look at the below ABAP code
    data: zVar(30)                type c value 'ZTEST_CLASS',
            methodName(30)    type c value 'Test_Method'.
    Question # 1:  Can I define the objVar as below or is there anyother way to accomplish this?
    data:  objVar  TYPE REF TO  zVar.  (Please note that zVar is the variable that contains the name of the 
                                                           class)
    Question # 2: Can I create the object objVar from the above question as below?
    CREATE OBJECT objVar.
    Question # 3: Can I call the method of objVar as below
    CALL METHOD objVar->Test_Method (please note that test method is a variable that contains the name
                                                             of the actual method)
    Thanks in advance.
    Regards

    All these Can be done using Dynamic programming.
    check this
    REPORT  ZTEST_CLASS.
    data: zVar(30) type c value 'ZCL_TEST1',  "<--class name
    methodName(30) type c value 'TEST'.   "<----Method name
    data: obj type ref to object.
    create object obj TYPE (zvar) .
    call method obj->(methodname).
    break-point.

  • CREATE OBJECT inside INITIALIZATION event in ABAP

    Hi everyone,
    I have one question, can we create object inside INITIALIZATION event. Why, I am asking this question is, because most of the time I have seen people to create object inside start-of-selection. Please give your thought on this.
    The code I have just coded below is also right or wrong?
    CLASS lcl_build_data DEFINITION.
       PUBLIC SECTION.
         METHODS : constructor,
                            get_all_files,
                             validate_site.
    *-- Private Section declaration
       PRIVATE SECTION.
             METHODS : clear_and_refresh,
                                display_output.
    ENDCLASS.                 
    *** class declaration,  create instance for the class
    DATA: gv_data     TYPE REF TO lcl_build_data.
    INITIALIZATION.
    *** Create class object. Constructor method will be called to Refresh
    *** and Clear all internal tables and Work areas
       CREATE OBJECT gv_data.
    *                    AT SELECTION-SCREEN             *
    AT SELECTION-SCREEN ON s_vkbur.
    *** Sales Office validation
       CALL METHOD gv_data->validate_site.
    *                START-OF-SELECTION                    *
    START-OF-SELECTION.
    *** Get the list of all files from unix dir.
       CALL METHOD gv_data->get_all_files.

    Since you are using the same object for your Selection screen related events, AT SELECTION-SCREEN, you would have to instantiate the object in the INITIALIZATION event. If your object usage is just for the data - In case you use the MVC design pattern, you should push back the object creation in START-OF-SELECTION.
    Regards,
    Naimesh Patel

  • Specific function modules to create objects of type SC, D, CG CE?

    Hi Experts,
    I need to create objects
    SC (Program of study)
    D   (Event Type)
    CG (Module Group)
    CE (Assessment)
    using function modules. Up to the present, we have beeing using function module
    HRIQ_OBJECT_CREATE
    as an all purpose FM for all these object types.
    However, now, I have the requirement to replace these FM with specific FM for that particular object type. For object type SM, I found
    HRIQ_RFC_MODULE_CREATE
    Now, I am asking you if there are such FM for the other objects in question as well??
    THANKS,
    Johannes

    Dear Johannes,
    Hereby some FM's that may help you out:
    - HRIQ_CREATE_ANY_OBJECT --> create any objject
    - HRIQ_SUBJECT_CREATE --> create SU
    - HRIQ_TRANSCRIPT_CREATE --> create EQ
    - HRIQ_STUDY_OBJECT_CREATE --> create CS
    - HRIQ_RULECONTAINER_CREATE --. create RC
    - HRIQ_AW_ACWORK_CREATE --> create CW
    br
    Rob

  • ClassNotFoundException when creating objects

    Hi, am am pretty new to using java reflection and all that stuff - so this could be a fairly obvious question.
    I am using reflection to create objects whose names are only known at runtime. The method is as follows:
        public static IGene getRandomGene(Vector genes){
            int size = genes.size();
            int rndOp = (int)Math.floor(Math.random() * size);
            String newClassName = (String)genes.get(rndOp);
            IGene newGene = null;
            try {
                Class geneDefinition = Class.forName(newClassName);
                Constructor cons = geneDefinition.getConstructor(new Class[0]);
                newGene = (IGene)GeneUtils.createObject(cons, new Object[0]);
            } catch (ClassNotFoundException e) {
                System.out.println(e); //And the ClassNotFoundException is encountered
            } catch (NoSuchMethodException e) {
                System.out.println(e);
            return (OperatorGene)newGene;
        }The name of the class to be created (newClassName) is found fine.
    My includes are:
    package simplegp;
    import java.util.Vector;
    import java.lang.reflect.*;
    import simplegp.operandGenes.*;
    import simplegp.operatorGenes.*;
    import simplegp.operatorGenes.doubleOps.*;
    import simplegp.operatorGenes.singleOps.*;These includes definatly cover the classes to be included.
    Am i maknig a silly mistake? I cannot fingure it out.
    Many thanks for any help
    Adam
    PS. The code is for some evolutionay programming, hence havnig Genes

    I seem to have solved the problem - sorry for not searching the forums first.
    I had to specify the class names as:
    simplegp.operandGenes.IntOperandGene
    Rather than just: IntOperandGene
    adam

  • Error creating Objects with Reflection

    This is the code:
    try{
         System.out.println("Restart - test 1 - sub == " + sub);
         c = Class.forName(sub);
         con = c.getDeclaredConstructor();
    catch(NoSuchMethodException e){
         System.out.println("Unknown event type\t" + e);
    }Output:
    Restart - test 1 - sub == Mouse
    Unknown event type     java.lang.NoSuchMethodException: Mouse.<init>()I have a Mouse class with a declared Constructor. Why can't it find the Constructor?

    SquareBox wrote:
    almightywiz wrote:
    Your code is trying to find the default constructor for your Mouse class. If you don't have a default constructor specified, it will throw the exception you encountered. What does your constructor signature look like?
    public Mouse(int weight){
         this.weight = weight;
    }How do I get the Constructor if it contains parameters?This is answered in your other thread: Creating objects with relfections And you even marked it correct!
    Please don't post the same question multiple times. It leads to people wasting their time duplicating each others' answers, and makes for a fractured discussion.
    Edited by: jverd on Apr 26, 2011 3:59 PM

  • Visual Basic 6 application moved to new server - activex component can't create object

    I have to move a VB6 application that was running on a Windows 2003 machine to a new Windows 2008 machine.
    This EXE application was using classes defined in a DLL using the Createobject method.
    Now, after the class instance has been created by Createobject, when the program calls the methods error 429 "activex component can't create object" is issued.
    The DLL has been registered on the new server using the command :
    regsvr32 c:\folderx\dllname.dll
    Which is the right forum to get help on this ?
    Thanks.

    Hello,
    As Dave says, VB 6 is no longer supported by Microsoft.
    I’d suggest asking in one of the following third-party forums which support Visual Basic 6.
    VB forums
    VB City
    For further information, see:
    Where to post your VB 6 questions
    Karl
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog: Unlock PowerShell
    My Book:
    Windows PowerShell 2.0 Bible
    My E-mail: -join ('6F6C646B61726C406F75746C6F6F6B2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

  • Run-time error '429': ActiveX component can't create object

    HI,
    I am having the following error in my Excel VBA Run-time error '429': ActiveX component can't create object  when running the following code:
    Dim objDistiller As New ACRODISTXLib.PdfDistiller6
    objDistiller.FileToPDF2 filePath & ".PS", filePath & ".PDF", "T:\Templates\PDFSettings\Standard.joboptions", 1
    This code has been working for years on all our systems, but due to recent security issues our administrator changed all user accounts to not have local administrator rights and now when we run this code we get the above error message.
    I have had a look at DComcnfg.exe to try and get it to work by setting the default property permissions to allow access by Everyone but I am still getting the error.
    Any help would be greatly appreciated.
    Regards.
    Shane Chapman.

    Hi Shane,
    Here is another way to create PDF with Macro using another API than Distiller. This API is faster too.
    Probably this post is not of interest anymore but here is how I have done it:
    1. Download PDFCreator: http://sourceforge.net/projects/pdfcreator/
    2. Use the following Macro:
    Option Explicit
    Sub printPDFmacro()
    'Author : Ken Puls (www.excelguru.ca)
    'Macro Purpose: Print to PDF file using PDFCreator
    ' (Download from http://sourceforge.net/projects/pdfcreator/)
    ' Designed for early bind, set reference to PDFCreator
    Dim pdfjob As PDFCreator.clsPDFCreator
    Dim sPDFName As String
    Dim sPDFPath As String
    '/// Change the output file name here! ///
    sPDFName = "Facture-" & nclient2 & " le " & Format(Date, "yyyy-mm-dd") & ".pdf"
    sPDFPath = "E:\Partenaire Scolaire\Comptabilite\Factures"
    PDFFileName2 = sPDFPath & "\" & sPDFName
    Set pdfjob = New PDFCreator.clsPDFCreator
    With pdfjob
    If .cStart("/NoProcessingAtStartup") = False Then
    MsgBox "Can't initialize PDFCreator.", vbCritical + _
    vbOKOnly, "PrtPDFCreator"
    Exit Sub
    End If
    .cOption("UseAutosave") = 1
    .cOption("UseAutosaveDirectory") = 1
    .cOption("AutosaveDirectory") = sPDFPath
    .cOption("AutosaveFilename") = sPDFName
    .cOption("AutosaveFormat") = 0 ' 0 = PDF
    .cClearCache
    End With
    'Print the document to PDF
    ActiveSheet.PrintOut copies:=1, ActivePrinter:="PDFCreator"
    'Wait until the print job has entered the print queue
    Do Until pdfjob.cCountOfPrintjobs = 1
    DoEvents
    Loop
    pdfjob.cPrinterStop = False
    'Wait until PDF creator is finished then release the objects
    Do Until pdfjob.cCountOfPrintjobs = 0
    DoEvents
    Loop
    pdfjob.cClose
    Set pdfjob = Nothing
    end sub
    Have any questions, just have to poke me.
    Michael

  • How Tomcat Webserver Create objects of ServletRequest and Response

    Tomcat webserver creates objects of ServletRequest and Response before calling the service method
    How the statement is declared plz help me

    ServletRequest and ServletResponse are interfaces. They are part of the Servlet API. Another parties can implement the API to their taste. Such as Apache Tomcat and Sun Glassfish. Apache Tomcat has its own implementations of the both interfaces, for example the org.apache.catalina.connector.Request and org.apache.catalina.connector.Response.
    So they can just do it like follows:
    javax.servlet.ServletRequest request = new org.apache.catalina.connector.Request();Apache Tomcat is open source. You can download the sources and look how they did it.
    Having said that, whenever someone asks this question, they generally want to be able to create the ServletRequest in a plain vanilla Java class outside the ServletContext. Is this true? If so, please elaborate about your actual problem. Just because this indicates a bad design.

Maybe you are looking for