Static or Instance methods

Hi,
I am a self-taught Java programmer and have been writing Java code over the past 18 months. I am comfortable with general coding, but I am having great difficulty deciding whether a method should be static or instance.
In many cases, I decide to create a class which has maybe 1 or 2 methods. A good example of this is the class I wrote which allows me to pass it a JFrame and it then centres the JFrame on screen. Seems to me I can do 1 of 2 things.
1. Put the code in the class constructor and then call it with:
CentreMe cm = new CentreMe(this);
where CentreMe is the name of the class and this refers to the JFrame that is being passed
2. Put the code in a static method within the class and then call it with:
CentreMe.CenterFrame(this);
Assuming that all the CentreMe class does is to centre a frame in this way, which is the correct (or at least best) approach. Seems to me there is no point in creating objects as per option 1 when they are never used therafter?
If anyone has advice or a URL that deals with this particular "design" issue I would be very grateful.
Thanks
Mark

Given that design, then your intuition is correct, that method should be static. No need for objects there. But on a higher level, the design is backwards. Instead of having a separate class that knows how to centre a JFrame, it would be better to create a subclass of JFrame that knows how to centre itself. Have a look at Bruce Eckel's online book "Thinking in Java" ( http://www.bruceeckel.com ); it has a lot of useful information about the design of objects.

Similar Messages

  • Name space conflict between static and instance method

    Hello,
    there seems to be a very unfortunate name space conflict between static and instance method name. Consider:
    static String description() that should return a description of a class.
    String description() that should return a description of an instance.
    That seems to confuse the compiler. How come? Static and instance methods don't have anything to get confused about.
    Thanks for any insights :-)

    Umm...jeez.
    It's not a bug, it's the way it's supposed to be.
    Since a static method can be called the same way an instance method
    A instance = new A();
    A.staticMethod();
    instance.staticMethod();it's not allowed.
    Also in the class, you can call
    public void myMethod() {
          instanceMethodInClass();        // You don't need this, it's superfluous
          staticMethodInClass();          // You don't need the class name.
    }If you didn't understand, then just accept the fact that it is so. Some day you'll understand it.

  • 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

  • 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);
    }

  • 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.

  • Set static or instance on level of methods in class?

    Hi,
      Can anyone tell me to set the level of method in class, which is better, static or instance?Because if set static, I don't need to create instance for a class, but I don't know it's advantage and disadvantage.

    Hi,
    There is no rule, it depends on your requirement. Usually you create STATIC methods for UTILITY classes like CL_GUI_FRONTEND_SERVICES or MATHS functions.
    If its dependent on a business object, then it makes sense for a instance method, as its dependent on the object it does not make sense that to be static.
    Regards,
    Ravi
    Note : Please mark the helpful answers

  • 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

  • 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.

  • How to call a instance method without creating the instance of a class

    class ...EXCH_PRD_VERT_NN_MODEL definition
    public section.
      methods CONSTRUCTOR
        importing
          value(I_ALV_RECORDS) type ..../EXCH_VBEL_TT_ALV
          value(I_HEADER) type EDIDC .
      methods QUERY
        importing
          I_IDEX type FLAG
          i_..........
        returning
          value(R_RESULTS) type .../EXCH_VBEL_TT_ALV .
    Both methods are instance methods.
    But in my program i cannot created instance of the class unless i get the results from Query.
    I proposed that Query must be static, and once we get results we can create object of the class by pasing the result table which we get from method query.
    But i must not change the method Query to a static method.
    Is there any way out other than making method Query as static ?
    Regards.

    You can't execute any instance method without creating instance of the class.
    In your scenario, if you don't want to process your method of your class, you can check the instance has been created or not.
    Like:
    IF IT_QUERY IS NOT INITIAL.
      CRATE OBJECT O_QUERY EXPORTING......
    ENDIF.
    IF O_QUERY IS NOT INITIAL.
    CALL METHOD O_QUERY->QUERY EXPORTING....
    ENDIF.
    Regards,
    Naimesh Patel

  • Can't make static reference to method while it is static

    Hello, can somebody please help me with my problem. I created a jsp page wich includes a .java file I wrote. In this JSP I called a method in the class I created. It worked but when I made the method static and adjusted the calling of the method it started to complain while i didnt make an instance of the class. the error is:Can't make static reference to method
    here is the code for the class and jsp:
    public class PhoneCheckHelper {
    public static String checkPhoneNumber(String phoneNumber) {
    String newPhoneNumber ="";
    for(int i=0; i<phoneNumber.length(); i++) {
    char ch = phoneNumber.charAt(i);
    if(Character.isDigit(ch)) {
    newPhoneNumber += String.valueOf(ch);
    return newPhoneNumber;
    <html>
    <head>
    <title>phonecheck_handler jsp pagina</title>
    <%@page import="java.util.*,com.twofoldmedia.text.*, java.lang.*" %>
    </head>
    <body>
    <input type="text" value="<%= PhoneCheckHelper.checkPhoneNumber(request.getParameter("phonenumberfield")) %>">
    </body>
    </html>

    Go over to the "New to Java" forum where that message is frequently explained. Do a search if you don't see it in the first page of posts.

  • Can't make static reference to method

    hi all,
    pls help me in the code i'm getting
    " can't make static reference to method....."
    kindly help me
    the following code gives the error:
    import java.rmi.*;
    import java.rmi.Naming;
    import java.rmi.RemoteException;
    import java.io.*;
    import java.io.IOException;
    import java.io.LineNumberReader;
    public class client
    static String vcno;
    static String vpin;
    static String vamt;
    static String vordid;
    static String vptype;
    //static String vreq;
    static String vreq = "1";
    static String vorgid;
    static String vm1;
    static String vs1;
    static String vqty1;
    static String vm2;
    static String vs2;
    static String vqty2;
    static String vm3;
    static String vs3;
    static String vqty3;
    static String vm4;
    static String vs4;
    static String vqty4;
    public static void main(String args[])
    try
    ServerIntf serverintf=(ServerIntf)Naming.lookup("rmi://shafeeq/server");
    int c;
    StringBuffer sb;
    FileReader f1=new FileReader("c:/testin.txt");
    sb=new StringBuffer();
    int line=0;
    while ((c=f1.read())!=-1) {
    sb.append((char)c);
    LineNumberReader inLines = new LineNumberReader(f1);
    String inputline;
    String test;
    while((inputline=inLines.readLine())!=null)
    line=inLines.getLineNumber();
    switch(line)
    case 1: {
    vcno = inLines.readLine();
    System.out.println(vcno);
    case 2: {
    vpin = inLines.readLine();
    System.out.println(vpin);
    case 3: {
    vptype = inLines.readLine();
    System.out.println(vptype);
    case 4: {
    vamt = inLines.readLine();
    System.out.println(vamt);
    case 5: {
    vordid = inLines.readLine();
    System.out.println(vordid);
    case 6: {
    vorgid = inLines.readLine();
    System.out.println(vorgid);
         case 7: {
    vm1 = inLines.readLine();
    System.out.println(vm1);
         case 8: {
    vs1 = inLines.readLine();
    System.out.println(vs1);
         case 9: {
    vqty1 = inLines.readLine();
    System.out.println(vqty1);
         case 10: {
    vm2 = inLines.readLine();
    System.out.println(vm2);
         case 11: {
    vs2 = inLines.readLine();
    System.out.println(vs2);
    case 12: {
    vqty2 = inLines.readLine();
    System.out.println(vqty2);
    case 13: {
    vm3 = inLines.readLine();
    System.out.println(vm3);
         case 14: {
    vs3 = inLines.readLine();
    System.out.println(vs3);
    case 15: {
    vqty3 = inLines.readLine();
    System.out.println(vqty3);
    case 16: {
    vm4 = inLines.readLine();
    System.out.println(vm4);
    case 17: {
    vs4 = inLines.readLine();
    System.out.println(vs4);
    case 18: {
    vqty4 = inLines.readLine();
    System.out.println(vqty4);
    f1.close();
    FileWriter f2=new FileWriter("c:/testout.txt");
    String t;
    t=ServerIntf.add(vcno,vpin,vamt,vordid,vptype,vreq,vorgid,vm1,vs1,vqty1,vm2,vs2, vqty2,vm3,vs3,vqty3,vm4,vs4,vqty4);
    String str1 = " >>";
    str1 = t + str1;
    f2.write(str1);
    System.out.println('\n'+"c:/testout.txt File updated");
    f2.close();
    catch(Exception e)
    System.out.println("Error " +e);

    Yes, ServerIntf is the interface type. The instance serverIntf. You declared it somewhere at the top of the routine.
    So what you must do is call t=serverIntf.add(...)This is probably just a mistype.

  • How can I use instance methods created with HashMap

    class Template
    static HashMap customer;
    a few methods created various customer
    public static display() //to display a particular customer information among i've created above
                 String objectName,currentObjectName;
              Customer customer;
              Scanner scan=new Scanner(System.in);
              System.out.print("Please enter the customer name");
              objectName=scan.nextLine();
              Iterator iteratorForCustomer=CustomerMap.entrySet().iterator();
              Map.Entry customerEntry=(Map.Entry)iteratorForCustomer.next();
             while(iteratorForCustomer.hasNext())
                    customerEntry=(Map.Entry)iteratorForCustomer.next();
                    if(objectName.equals((String)customerEntry.getValue()))
              System.out.println("Name : " +customer.getName()); //I'm trying to reference to an instance method getName() here but i can't do that .
    }The problem is I've created as many as I want and later in the program I tried to redisplay a particular customer information based on the input (objectName). User type in the objectName and I tried to look for a particular customer Object in the HashMap and display only the relevant customer information. Is there any way to do it ? Thanks everyone in advance.

    Peter__Lawrey wrote:
    use the get method
    [http://www.google.co.uk/search?q=map+tutorial+java]
    [http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html]
    And then either look at a generics tutorial, or, if you're stuck on a pre-1.5 version of Java, find out about casting

  • Calling Instance Method in a Global Class

    Hi All,
    Please can you tell me how to call a instance method created in a global class in different program.
    This is the code which I have written,
    data: g_cl type ref to <global class>.
    call method g_cl -> <method name>
    I am not able to create Create object <object>.
    It is throwing the error message " Instance class cannot be called outside...."
    Please can anybody help me..
    *Text deleted by moderator*
    Thanks
    Sushmitha

    Hi susmitha,
    1.
    data: g_cl type ref to <global class>.
    2.
    Create object <object>.
    3.
    call method g_cl -> <method name>.
    if still you are getting error.
    then first check that method level and visibility in se24.
    1.if  level is static you can not call it threw object.
    2. if visibility is protected or private then you can not  call it directly.
    If still you are facing same problem please paste the in this thread so that i can help you better.
    Regards.
    Punit
    Edited by: Punit Singh on Nov 3, 2008 11:54 AM

  • Static context error, nothing declared static, new instance isn't working

    I'm trying to get the IP address of a user using my applet. Nothing in my code is declared static.
    InetAddress IP = InetAddress.getAddress();I get non-static method getAddress cannot be referenced from a static context.
    I just read on another post with someone having a similar but not identical problem and someone replied saying you need to create a new instance. So I tried this:
    InetAddress IP = new InetAddress();
    //IP.getAddress();With this, I get the error: InetAddress(); is not public in java.net.InetAddress; cannot be accessed from an outside package
    What can I do? It's probably something simple.
    If you need code just ask, there's just alot of code and it might take awhile to recreate it.

    I'm trying to get the IP address of a user using my
    applet. Nothing in my code is declared static.
    InetAddress IP = InetAddress.getAddress();I get non-static method getAddress cannot be
    referenced from a static context.
    I just read on another post with someone having a
    similar but not identical problem and someone replied
    saying you need to create a new instance. So I tried
    this:
    InetAddress IP = new InetAddress();
    //IP.getAddress();With this, I get the error: InetAddress(); is not
    public in java.net.InetAddress; cannot be accessed
    from an outside package
    What can I do? It's probably something simple.
    If you need code just ask, there's just alot of code
    and it might take awhile to recreate it.In your first try the method you attempted to use can only be used in an instant of an InetAddress ie. ip.getAddress(). Therefore the compiler thought you were trying to call a static method that was really an instance method. On your second try you used the contructor of InetAddress which isn't public, so you can't use it. To make an InetAddress use any of the static methods of the InetAddress, which can be found at http://java.sun.com/j2se/1.4.1/docs/api/java/net/InetAddress.html

  • Private instance method

    I want to have a private instance method in my application that changes the values of some variables. Then I want to use these variables in the main method. Is it possible to do this?
    When I tried to do it, I recieved the following error message:
    non-static variable cannot be accessed in static context
    Can anybody help me?

    import java.util.*;
    public class Test {
      public static void main(String[] args) {
        Test test = new Test();
        test.showData();
        test.setMyString("xyz");
        test.setMyInt(55);
        System.out.println("Main1 - myInt="+test.getMyInt()+", myString="+test.getMyString());
        test.mungeData();
        System.out.println("Main2 - myInt="+test.getMyInt()+", myString="+test.getMyString());
      private int myInt = 3;
      private String myString = "abc";
      public Test() { }
      public String getMyString() { return myString; }
      public void setMyString(String s) { myString = s; }
      public int getMyInt() { return myInt; }
      public void setMyInt(int i) { myInt = i; }
      public void mungeData() { myInt++; myString+="x"; }
      public void showData() { System.out.println("Test - myInt="+myInt+", myString="+myString); }
    }

Maybe you are looking for

  • How to print to a specific printer tray

    Post Author: hoochpit CA Forum: Administration I have a customer that wants the same report to print to different printer trays depending on parameters sent it.  We have no problem recognizing which tray it should go to, but cannot get it to print to

  • External disks (Firewire/USB) won't boot in late Macbook Pro 2013, but do work in earlier Mac's. How to fix it?

    Hi It always worked, till now. If I sell a Apple notebook because I bought a new one, I make a clone with CCC and with Command-R or Choose Startup disk I say to the new machine: now eat this, here's my old stuff. It's a great way of upgrading to a ne

  • Restrict  Values shown in Dropdown Lists - Web Layout

    Hello, We currently have a requirement in our BPS application, where the users want the list in a dropdown to be restricted to only those values for which no planning has been carried out. Example. We have master data for Project IDs. While inserting

  • Mouse double click event

    hi im really new to programming, i have a jlist populated from ms-access,i just want to capture a event only when the item is double clicked. can anybody please get me the code for capturing the data only when the mouse is double clicked. -thanks

  • I'm missing the Apple Mobile Device USB Driver.. iPhone isn't recognized in iTunes?

    I have tried re-installing itunes, restarting computer/ phone, disabling security software, different USB cords, etc.. I followed a page on apple (http://support.apple.com/kb/TS1538) and concluded I am missing the driver but none of the suggestions h