Write to static field from instance method

instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.
public static loadingDialog StatusWndw = null;
StatusWndw = new loadingDialog(this);
iwant to acces this satic field out side the class.
how to slove this problem

Make the LoadingDialog a singleton class. Lookup the singleton pattern.

Similar Messages

  • Accessing static context from instances...

    Hello,
    I'm confused with something. Accessing static elemnts or static methods from an instance is allowed. I think it shouldn't be allowed. Because static context is class-wide so objects shouldn't be able to access them.
    Am I wrong..?

    I find it confusing.. If something is class-wide then
    it should only be accessed by the class, not the
    instance of the class...That depends on the nature or purpose of the information. Static information or methods are a useful way of sharing information between instances of the same class, while still having that information protected from other classes. Other examples are constants which are used within each instance. Why should each instance have a separate copy of exactly the same constant?
    You could even argue that any method which does not need any instance information should be declared static, but it is not always necessary to make that distinction.
    Eclipse (mine at least :) ) gives a warning when you access a static
    method/variable 'through' an instance, telling you that you should access >the method/variable in a static way.This warning usually occurs if you call a static method in a non static way. For example, if you declare a class called MyClass with a static method myMethod() and you have an instance assigned to variable anInstance, you should call the method using MyClass.myMethod() instead of anInstance.myMethod().
    Graeme

  • Interfaces: static variables but instance methods, why?

    Why do variables need to be static in interfaces but the methods in them are not allowed to be static? Or, asked differently: Why methods must not be static while variables have to be static in interfaces?
    I don't understand the reason for that difference.

    An interface defines functionality but can not be instantiated as an object. So for the static variables, it can define variables that can be accessed by all implementing classes, but there can only be one definition of them, hence static. Non-static variables fall in the realm of implementation, which is not what interfaces are for.
    Static methods are used to define an implementation that is common among all instances of an object, and must be implemented when defined. Since interfaces can not provide any implementation, static methods are invalid. Remember that static methods are commonly used without instantiating an object (like java.lang.Math methods) so the implementation must be provided when defined.

  • Changing fields from run() method

    I have some threads in my program. There is one which in his run() method changes field of other class, my problem is that the change appears with some dealay. In my opinion the delay is to long. Is there any way to make it faster??
    Thanks for reply.
    Greg.

    I think can... u can set the timeslice of the thread to run faster... try looking it here...
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html
    Hope it helps!

  • Can one combine static and instance methods?

    Hi,
    Can one define a method so that is can be used as both a static or an instance method?
    Basically I'm trying to simplify my class to so that I can call a method either statically with parameters or instantiated using it's own attributes.
    In other words, I'm trying to accomplish both of these with one method:
    zcl_myclass=>do_something_static( im_key = '1234' ).
    lv_myclass_instance->do_something( ).   " key in private attributes
    Why would I want to do that?
    I would like to avoid instantiation in some cases for performance reasons and would like to keep it simple by having only one method to do basically the same thing.
    Any input or alternative suggestions welcome.
    Cheers,
    Mike

    Ok, I may be reaching here a bit, I know, but maybe this may give you some ideas.  After creating the object, pass it back to the method call.
    report zrich_0001.
    *       CLASS lcl_app DEFINITION
    class lcl_app definition.
      public section.
        data: a_attribute type string.
        class-methods: do_something importing im_str type string
                                   im_ref type ref to lcl_app optional.
    endclass.
    *       CLASS lcl_app IMPLEMENTATION
    class lcl_app implementation.
      method do_something.
        if not im_ref is initial.
           im_ref->a_attribute = im_str.
          write:/ 'Do_Something - ',  im_ref->a_attribute.
        else.
          write:/ 'Do_Something - ',  im_str.
        endif.
      endmethod.
    endclass.
    data: o_app type ref to lcl_app.
    start-of-selection.
      create object o_app.
      call method o_app->do_something(
               exporting
                   im_str = 'Instansiated'
                   im_ref = o_app ).
      call method lcl_app=>do_something(
               exporting
                   im_str = 'Static' ).
    Regards,
    Rich Heilman

  • Calling non-static command from within static method

    Hello,
    I have a static method that reads bytes from serial port, and I want to set a jTextField from within this method. but I get error that says it is not possible to call non static method from a static one. How can it be solved?

    ashkan.ekhtiari wrote:
    No, MTTjTextField is the name of jTextFiled class instance.You haven't declared any such variable in the class you posted, not to mention that such a variable name violates standard code conventions.
    This is and instance of that object actually. You haven't declared any such variable in the class you posted.
    the problem is something else. No, it isn't, based on the information you have provided. If you want accurate guidance, don't post misleading information about your problem.
    It can not be set from within static method.A question commonly asked on Java forums concerns an error message similar to the following:
    non-static variable cannot be referenced from a static context
    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term instance is often substituted for non-static, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    Once you understand this concept, you can fix your own problem.
    ~

  • Avoid assigning to servlet static fields without using a shared lock??

    Hi
    i received the following warning on my code, does anyone give me a help on this? Thanks
    "Avoid assigning to servlet static fields from javax.servlet.Service.service () without using a shared lock."
    And my code are as follow:
    public class MyDataSource {
        private static DataSource ds = null;
        public static DataSource getDataSource() throws NamingException, Exception
            if (ds==null){
                   InitialContext ctx = new InitialContext();
                try{
                    synchronized(getDataSource()){
                    if(ds==null){
                        ds = (DataSource) ctx.lookup(SysProperties.ds);
                } catch (Exception ex) {
                    throw new Exception("DBConnection Exception: " +ex.toString());
                }finally{
                        if(ctx !=null){
                            ctx.close();
            return ds;       
    }

    The service method of a servlet is multi-threaded to handle multiple requests. Hence,any static or public fields accessed by the service method should be restricted to a single thread access (for example using synchronized keyword) to make it thread-safe. That is why you are getting the warning message.

  • Static field initialization

    Ok, I know this was a good practices issue in C++, where order of initializing static fields from different source files was unknown, but I'm not sure if Java is smart enough to figure it out.
    So, say you have in one file
    public class A{
       public static B b = new B();
    }And in the other:
    public class C{
       private static D  d = A.b.getD();
    }Will this always work? Or does it depend on the order in wich classes A and C are loaded.

    jschell wrote:
    In multiple threads on some systems (potentially) the construction of B() is not guaranted before access to 'b' is allowed.Class initialization is synchronized, so the construction of B() should be fully visible to other threads without explicit synchronization or making the field final.
    From JLS 12.4.3:
    Code generators need to preserve the points of possible initialization of a class or interface, inserting an invocation of the initialization procedure just described. If this initialization procedure completes normally and the Class object is fully initialized and ready for use, then the invocation of the initialization procedure is no longer necessary and it may be eliminated from the code-for example, by patching it out or otherwise regenerating the code.So class initialization is attempted whenever the code generator feels it might be the first use of a class.
    And from 12.4.2:
    The procedure for initializing a class or interface is then as follows:
    1. Synchronize (§14.19) on the Class object that represents the class or interface to be initialized. This involves waiting until the current thread can obtain the lock for that object (§17.1).
    2. If initialization is in progress for the class or interface by some other thread, then wait on this Class object (which temporarily releases the lock). When the current thread awakens from the wait, repeat this step.So the class is synchronized on until initialization (which includes all static initializers) finishes. This makes possible the class holder idiom for singletons.

  • This static method cannot hide the instance method from...

    What means the error message "This static method cannot hide the instance method from Referee"?
    Referee.java is a interface. I implemented it in the class RefereeMyName.java and made a method in that class to be static. Thats why I received that error message.
    But can't I use static methods when I have implemented a interface in that class? I want to have a Player.java class which I want to access RefereeMyName.getTarget(). I cannot use a instance instead because I wouldn't receive a valid return value then (RefereeMyName is the client class).
    What is the solution?

    Hi,
    Well i do not think that you can do that b'cos that way you are not giving the same signature for the method as that exists in the interface. I do not know how other way it can be done but if something urgent for you then you can remove that method from that interface and only define in the class.
    Regards,
    Shishank

  • Static field changes for both instances

    Whenever I construct a new object with a static field or use a set method on any of the instances of that object, the static field will change to the last modification made. In the case of my program, whenever the static String color field is changed to the last modification made. This only happens with the static fields, the other fields work just fine.
    Why does this problem occur?

    Sorry, I can't understand the question. If you have lots of different objects, all of the same class, they all share one copy of the static field, so if you invoke a method that changes the static field on one instance, all the other instances will see that change.
    if you don't want this behaviour, don't make the field static; then each instance will have its own copy of the field.

  • Instance methods faster than sync. static methods in threaded env?

    consider the following please:
    (-) i have "lots" of instances of a single Runnable class running concurrently..
    (-) each instance uses a common method: "exponential smoothing" and they do a lot of smoothing.
    so:
    (option #1): include a "smooth()" instance method in the Runnable class.
    (option #2): include a "smooth()" synchronized static method in the Runnable class.
    (option #3): create a MathUtility class, and have "smooth()" as an instance method in this class.
    (option #4): make "smooth()" a synchronized static method in the MathUtility class.
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??
    well, i can't image there would be a measurable difference so maybe i should not post.
    but, if there is a flaw in my thinking, please let me know.
    thanks.

    kogose wrote:
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".From an OOP point of view you should probably have a class that represents the data that provides a (non-static) smooth() method that either modifies the data or returns a new smoothed data object (depending on whether you want your data objects to be immutable or not).
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??No, methods are not "copied" for each instance. That just doesn't happen.
    well, i can't image there would be a measurable difference so maybe i should not post.If you don't know, then you should probably try it.
    but, if there is a flaw in my thinking, please let me know.The flaw in your thinking is that you can think that you can intuitively grasp the difference in performance of a change at that level.
    I have yet to meet anyone who can reliably do that.
    Performance optimization is not an intuitive task at that level and you should never do performance optimizations without proving that they are improvements for your particular use case.
    First part: Is the smooth() method really thread-unsafe? Does it use some shared state? My guess would be that it uses only local state and therefore doesn't need any synchronization at all. That would also be the fastest alternative, most likely.

  • Purpose of declaring the method or class or static and as instance

    what is the purpose of declaring a method in a class or the class itself as static.
    Does it mean we cannot create a copy of that class or method if we declare it as static.
    if so then why do they dont want that class to be created as a copy ?
    Why do they want to declare a class as static
    please provide some conceptual undersatnding regarding the static and instance class with one example

    Static methods are often used for the implementation of utility methods. Please have a look at the class CL_ABAP_CHAR_UTILITIES for example.
    You use the methods of this class in the same way as you would use a function in ABAP (like
    LINES( itab )
    ). You use it in a static way because the functionality is always the same no matter in what context you are calling the function.
    The purpose of instance methods is that their logic is in some way related to an attribute of the object instance that you use to call it.
    For example, you create an instance of object PO (a purchase order) called MY_PO. Then the method
    MY_PO->ADD_POSITION
    would add a position to a concrete PO that has a unique number etc. But if the object has a static method DELETE_POSITION then it just deletes the current position of a PO, regardless on which concrete PO you are acting at the moment.
    I hope this clarifies it for you.
    Regards,
    Mark

  • Should I use a static method or an instance method?

    Just a simple function to look at a HashMap and tell how many non-null entries.
    This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
    Does this have to be an instance method? Or is it perfectly fine to use a static method?
    public static int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    OR
    public int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    }

    TPD Opitz-Consulting com wrote:
    The question is the other way around: Is there a good reason to make the method static?
    Ususally the answer is: no.The question is: does this method need state? Yes -> method of a class with that state. No -> static.
    The good thing of having this method statig is that it meight decrese memory foot pring but unless you're facing memory related problem you should not think about that.I doubt there is any difference between the memory foot print of a static or not method.
    I'm not shure if this method beeing static maks problems in multithreaded environments like the one you're aiming at. But I do know that an immutable object is always thread save.Does the method use shared state (data)? No -> no multi threaded problems.
    Can the parameters be modified by different threads? Yes, if multiple threads modified the parameter map, but nothing you can do about it here (no way to force the calling thread to lock on whatever you lock on).
    So my answer to your question is: yes, it should be non static.The method should be static since it uses no state.
    It is thread-safe when only the calling thread can modify the passed map (using a synchronized or ConcurrentHashMap is not enough, since you don't call a single atomic method on the map).
    // Better use Map instead of HashMap
    // We don't care about the generic type, but that does not mean we should use a raw type
    public static int countNonNullEntries(Map<?, ?> map) {
      // whether to accept null map or not, no need for explicit exception
      // since next statement throw NPE anyway
      Collection<?> values = map.values();
      // note your method is called countNonNull, not countNull!
      // (original code it would need to by if(null != mapValue) notNullsCounter++;
      return values.size() - java.util.Collections.frequency(values, null);
    }

  • I need to add a single field from with_item table . need to write select query with reference to company code , account doc no , fiscal year

    I need to add a single field from with_item table . need to write select query with reference to company code , account doc no , fiscal year

    Hi Arun ,
    Can you explain little bit more ??
    what is account doc no? 
    what are the transactions should be displayed in your output??
    -Rajesh N

  • Write fields from two tables in one line??

    Hi friends,
    I want to write some fields from bkpf and bseg in one line...
    My report should like something like this:
    ****some text*****
    *for first document*******  bkpf-bldat  kunnr  bseg-belnr    bseg-gsber   bseg-wrbtr     
    *for second document***  bkpf-bldat  kunnr  bseg-belnr    bseg-gsber   bseg-wrbtr     
    *for third document******  bkpf-bldat  kunnr  bseg-belnr    bseg-gsber   bseg-wrbtr  
    etc.
    What should I change in order to get this form in report output?? Can I put these fields in some table so that it looks like excel table??Could you please check out the code below?
      loop at it_bkpf into wa_bkpf.
      loop at it_bseg into wa_bseg.
      write: wa_bseg-gsber, wa_bseg-belnr, wa_bseg-wrbtr.
      endloop.
      write: wa_bkpf-bldat.
      read table it_bsid with key bukrs = wa_bkpf-bukrs
      belnr = wa_bkpf-belnr
      gjahr = wa_bkpf-gjahr
      cpudt = wa_bkpf-cpudt.
      if sy-subrc = 0.
      write: it_bsid-kunnr.
      endif.
      endloop.
    Thanks,
    Nihad

    hi nihad,
    define positions on where to write data like this.
    LOOP AT it_bkpf INTO wa_bkpf.
      LOOP AT it_bseg INTO wa_bseg WHERE belnr EQ wa_bkpf-belnr.
        WRITE: /5 wa_bkpf-bldat.
        READ TABLE it_bsid
        WITH KEY bukrs = wa_bkpf-bukrs
                         belnr = wa_bkpf-belnr
                         gjahr = wa_bkpf-gjahr
                         cpudt = wa_bkpf-cpudt.
        IF sy-subrc EQ 0.
           WRITE: 20 it_bsid-kunnr.
        ENDIF.
        WRITE: 35 it_bseg-belnr,
                    50 it_bseg-gsber,
                    60 it_bseg-wrbtr.
      ENDLOOP.
    ENDLOOP.
    regards,
    Peter

Maybe you are looking for

  • ITunes keeps changing to the default folder location

    I have no idea what's going on here, but, it's getting very frustrating. Here's the situation: I am running the latest version of iTunes (11.whatever) on Windows 7, and my default iTunes Library location is in My Music on my C:. Unfortunately, my C:

  • Keeping heading and detail on the same page

    Hi, I have a report with a group header section and a detail section.  How can I keep the heading section and all the detail section on the same page without starting each group on a new page? The detail section will have either 2 or 3 records with s

  • HELP!! Can's type in Firefox UNLESS I open another internet tab, then go back to the first tab.

    HELP!! Can's type in Firefox UNLESS I open another internet tab, then go back to the first tab! All of the sudden, out of the blue, I hear the little "beep" noise that Mac's make when, for example, you try to close a program without saving an item fi

  • Cannot add apps to iTunes Wish List for my ipod

    When using iTunes on my Macbook, I cannot add apps (for ipod, ipad, etc. NOT for computer) to my Wish List.  When I try, a pop up error alert box says that "Your request is temporarily unable to be processed., to try again later."  The odd thing is t

  • Smart Objects without tmp files

    I am trying to place/ import a .psd as a smart object into a composite and have Photoshop keep referenceing that same psd witout it creating a local tmp file. does anyone know fi this can be done? Thanks!