Static vs non static methods - best practice

I have a question with regards to program design.
If I have a class that looks something like:
public class SampleApp extends Engine implements Listener_OnMyEvent
public static void main(String argv[])
int x=10;
//Call metod1
Method1(x);
public method1(int i)
//Call a method from the Engine Class
//I know I don't have to have "Engine." here but it's just to
clearify
Engine.method2();
public void OnMyEvent()
Log("Event Hapended");
Let's say now that I want to move method1 to another class/file in
order to keep the code as neat and tidy as possible.
How should I do that? What is best practice according to you? Should
the methods there be static?
I tried to create:
public class MyMethods
public static method1(int i)
Engine.method2();
...but then method2 isn't available since Engine isn't implemented
unless I pass the whole class along:
MyMethods(x, this)
Is this correct?
I hope you see what I'm getting at here.
Any suggestions is appreciated.
Thanks

Then you would have a cyclic dependency which suggests a design error.
But other than that you just pass an instance of the first class when your construct the second one.

Similar Messages

  • Abstract method versus static and non-static methods

    For my own curiosity, what is an abstract method as opposed to static or non-static method?
    Thanks

    >
    Following this logic, is this why the "public static
    void main" 0r "Main" method always has to be used
    before can application can be run: because it belongs
    to the class (class file)?
    Yes! Obviously, when Java starts up, there are no instances around, so the initial method has to be a static (i.e. class) one. The name main comes from Java's close association with C.
    RObin

  • Static Vs Non-static methods

    Hello,
    I wonder what should I use. I have got a class which does a lot of counting.. I can put the methods inside the class or make a class Math3D with the static methods that will count it.
    Which is the better way?

    BigDaddyLoveHandles wrote:
    deepak_1your.com wrote:
    Sorry mate... did not get that.By definition a utility class has all static methods. So as soon as you mention "utility class" you've already made a decision. The real question is "should method X be static or non-static"? My default position is to assume no method should be static, and then wait to be convinced.
    Look at utility class java.lang.Math, for example. It has static methods sin(), cos(), sqrt(), etc... An obvious choice for a utility class, right? Then they introduced class StrictMath in 1.3 with exactly the same static method signatures. That's a code smell that one should have written an interface and implemented it in at least two ways, but it's too late for that because the original methods are static.Good post.

  • Static Verse Non-Static Methods

    Let say I was going to write a class that contained
    methods to do the same thing as itoa() and atoi() functions
    in C. What would be the pros and cons of making those
    methods static verses non-static?

    Many thanks to all.
    In summary, (correct me if I am wrong or misunderstood)
    1) methods only needs to be instance methods if they use/access
    instance variables, otherwise class/static methods are preferred
    because then, one does not have to create an instance of the
    object and keep track it.
    2) relative to threads, a method only needs to be synchronized
    if it uses/accesses shared data.
    3) most likely, not very efficient to write wrappers for one
    liners like: Integer.parseInt(String s); etc.

  • Static and non-static variables and methods

    Hi all,
    There's an excellent thread that outlines very clearly the differences between static and non-static:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=374018
    But I have to admit, that it still hasn't helped me solve my problem. There's obviously something I haven't yet grasped and if anyone could make it clear to me I would be most grateful.
    Bascially, I've got a servlet that instatiates a message system (ie starts it running), or, according to the action passed to it from the form, stops the message system, queries its status (ie finds out if its actually running or not) and, from time to time, writes the message system's progress to the browser.
    My skeleton code then looks like this:
    public class IMS extends HttpServlet
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            doPost(request, response);
       public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          //get the various parameters...
             if (user.equalsIgnoreCase(username) && pass.equalsIgnoreCase(password))
                if(action.equalsIgnoreCase("start"))
                    try
                        IMSRequest imsRequest = new IMSRequest();
                        imsRequest.startIMS(response);
                    catch(IOException ex)
                    catch(ClassNotFoundException ex)
                else if(action.equalsIgnoreCase("stop"))
                    try
                        StopIMS stopIMS = new StopIMS();
                        stopIMS.stop(response);
                    catch(IOException ex)
                 else if(action.equalsIgnoreCase("status"))
                    try
                        ViewStatus status = new ViewStatus();
                        status.view(response);
                    catch(IOException ex)
             else
                response.sendRedirect ("/IMS/wrongPassword.html");
    public class IMSRequest
    //a whole load of other variables   
      public  PrintWriter    out;
        public  int                 messageNumber;
        public  int                 n;
        public  boolean         status = false;  //surely this is a static variable?
        public  String            messageData = ""; // and perhaps this too?
        public IMSRequest()
        public void startIMS(HttpServletResponse response) throws IOException, ClassNotFoundException
            try
                response.setContentType("text/html");
                out = response.getWriter();
                for(n = 1 ; ; n++ )
                    getMessageInstance();
                    File file = new File("/Users/damian/Desktop/Test/stop_IMS");
                    if (n == 1 && file.exists())
                        file.delete();
                    else if (file.exists())
                        throw new ServletException();
                    try
                        databaseConnect();
                   catch (ClassNotFoundException e)
    //here I start to get compile problems, saying I can't access non-static methods from inside a static method               
                   out.println(FrontPage.displayHeader()); 
                    out.println("</BODY>\n</HTML>");
                    out.close();
                    Thread.sleep(1000);
            catch (Exception e)
        }OK, so, specifially, my problem is this:
    Do I assume that when I instantiate the object imsRequest thus;
    IMSRequest imsRequest = new IMSRequest();
    imsRequest.startIMS(response); I am no longer in a static method? That's what I thought. But the problem is that, in the class, IMSRequest I start to get compile problems saying that I can't access non-static variables from a static method, and so on and so on.
    I know I can cheat by changing these to static variables, but there are some specific variables that just shouldn't be static. It seems that something has escaped me. Can anyone point out what it is?
    Many thanks for your time and I will gladly post more code/explain my problem in more detail, if it helps you to explain it to me.
    Damian

    Can I just ask you one more question though?Okay, but I warn you: it's 1:00 a.m., I've been doing almost nothing but Java for about 18 hours, and I don't do servlets, so don't take any of this as gospel.
    If, however, from another class (FrontPage for
    example), I call ((new.IMSRequest().writeHTML) or
    something like that, then I'm creating a new instance
    of IMSRequest (right?)That's what new does, yes.
    and therefore I am never going
    to see the information I need from my original
    IMSRequest instance. Am I right on this?I don't know. That's up to you. What do you do with the existing IMS request when you create the new FrontPage? Is there another reference to it somewhere? I don't know enough about your design or the goal of your software to really answer.
    On the other hand, IMSRequest is designed to run
    continuously (prehaps for hours), so I don't really
    want to just print out a continuous stream of stuff to
    the browser. How can I though, every so often, call
    the status of this instance of this servlet?One possibility is to pass the existing IMSRequest to the FrontPage and have it use that one, rather than creating its own. Or is that not what you're asking? Again, I don't have enough details (or maybe just not enough functioning brain cells) to see how it all fits together.
    One thing that puzzles me here: It seems to me that FP uses IMSReq, but IMSReq also uses FP. Is that the case? Those two way dependencies can make things ugly in a hurry, and are often a sign of bad design. It may be perfectly valid for what you're doing, but you may want to look at it closely and see if there's a better way.

  • Static vs Non static

    Hi,
    I was just not clear as to how does the compiler handle Static members.
    As far as fields are concerned if they are declared static, they are created on the HEAP and are shared by all the class instances.
    However, what i want to know is what happenes to the methods. I mean methods are just piece of code so why should a non-static method be instantiated for all the instances?
    So, I presume that static members mean that they are created on the HEAP.
    Am i right here?
    Thanks
    Praveen

    ... not clear as to how does the compiler handles Static members.
    As far as fields are concerned if they are declared
    static, they are created on the HEAP
    Not exactly.
    Methods live in the class definition which lives in Perm Space.
    and are shared by all the class instances.Yes.
    However, what i want to know is what happenes to the
    methods. I mean methods are just piece of codeSee above.
    so why should a non-static method be instantiated for all the instances?'tisn't.
    Methods are not instantiated.
    So, I presume that static members mean
    that they are created on the HEAP.
    Am i right here?No.
    I asked WHAT happens in the background in case of static methods.Why does it matter?
    I mean methods are just piece of code.
    So why this difference, wheather the method is
    static or non-static
    should not make any difference.The magic 'this' keyword can only be used in non-static methods.
    What i want to say is
    there should be some sort of store where the method's
    code is put and called irrespective of whether the
    method is static or non-static
    It is called Perm Space.

  • Static vs Non--Static members

    I'm having some trouble trying to understand the differences between static and non-static members.
    I've read a few online information about static members, but I don't understand the purpose of static members.
    Can someone try to explain the main points of static members and the differences between static and non-static members?

    I'm having some trouble trying to understand the
    differences between static and non-static members.
    I've read a few online information about static
    members, but I don't understand the purpose of static
    members.
    Can someone try to explain the main points of static
    members and the differences between static and
    non-static members?Static means only one per class. If you have a Class and generate 20 objects of this class or more, they all share the same copies of any static variables. This is as opposed to instance variables of which each Object has its own. If an object changes one of its instance variables, this doesn't affect another object's instance variables.
    Having said this, however, vague and general questions are great if you are face to face with a tutor where you can have a conversation but are very difficult to answer in this format. Your best bet is to go through several online articles (and there are many good ones, just google for them) and then coming back with specific questions. Another option is to go through a book or two. Most have a chapter covering this.
    Message was edited by:
    petes1234

  • Static calling non-static

    What is the best way aroung a static main method trying to call a non static method?

    Fixing the design of the program, IMHO. This kind of a
    think does not happen in a poperly designed program.Exactly. IF a static method needs to access a non-static variable, it needs to specify which instance of its class owns the variable.
    public static void main(Sting EAGLES[]))
       MyJDialog  mjd = new MyJDialog();
       mjd.setSomeParameter(true);
    }Here's the Reader's Digest Condensed Version&#169; of the rules (with grammatical license):
    1. A static method may only access the static data of it's class, not non-static data.
    2. static methods can only call static methods, not non-static.
    3. There ain't no this in static methods.
    4. You can't override a static method to be non-static.

  • Help with static and non static references

    Hi all,
    I'm new to Java I'm having some difficulties with accessing non static methods.
    I'm working with Tree data structures and all the interfaces and methods are non-static.
    I have to write a tester main method to create and modify trees but how do I access the non static fields from main which is static?
    Any help would be appreciated
    Thanks.

    Create an Instance for that particular class then call the method using that instance.

  • Static vs. non-static errors!

    I dont understand why this doesn't work. Could someone explain the concept behind this error, and perhaps a solution, or another way of going about this?
    error:
    test.java:3: non-static method add(int,int) cannot be referenced from a static context
    add(1,2);
    ^
    1 error
    public class test {
       public static void main(String[] args) {
          add(1,2);
       public int add(int a, int b) {
          int c = a+b;
          return c;
    }

    You need to make your add() static:
    public static int add(int a, int b)
    Anything you reference in a static method - a method or a variable - that is defined ooutside of the static method must be defined as static. For example:
    public class test
    int x = 0;
    static int y =0;
    public static void main(String[] args)
    {      add(1,2); 
    System.out.println(x) // will cause an error - non-static variable referenced in static class
    System.out.println(y) // is okay
    public int add(int a, int b)
    {      int c = a+b;      return c;  
    }

  • Static to non-static

    Hello.
    I am trying a small die rolling program which pompts the user to enter the number of rolls in a specified range and print the frequency. Now, I want the results to be printed in a JTextArea but it doesn't work. I get cannot make a static reference to the non-static. If I use println() instead of setText(), it does print though.
    public static void main(String[] args){
              JFrame tFrame = new Roll();
              tFrame.setSize(600, 300);
              tFrame.setVisible(true);
              Random dice = new Random();
              int freq[] = new int[7];
              final int first = 1;
              final int limit = 10000;
         try{
              String enter = JOptionPane.showInputDialog(null, "Enter number of
                              rolls in range 1-10000");
              int range = Integer.parseInt(enter);
              if (range > limit){
                   JOptionPane.showMessageDialog(null, "You are not allowed
                             to enter an integer greater than 10000", "Error", JOptionPane.ERROR_MESSAGE);
                   System.exit(0);;
              if (range < first){
                   JOptionPane.showMessageDialog(null, "You cannot enter 0
                               or less than 1", "Error", JOptionPane.ERROR_MESSAGE);
                   System.exit(0);
              for(int i = 1; i < range+1; i++){
                   ++freq[1 + dice.nextInt(6)];
                   txt.setText("Result\tFrequency"); //<<<<cannot make a static reference
                   for (int result = 1; result < freq.length; result++){
                   txt.setText(result + "\t" + freq[result]);  //<<<<cannot make a static reference
              catch (final NumberFormatException nfe) {
                   JOptionPane.showMessageDialog(null, "Please
                              enter integer!", "Error", JOptionPane.ERROR_MESSAGE);
                   System.exit(0);
    }Help please?

    Whatever txt is: you can't call instance attributes or instance methods without actually having the instance first. That's what the compiler is trying to tell you.
    Consider having a main method like
    MyClass mc = new MyClass();
    mc.doStuff();In doStuff() you can then access all the non-static attributes and methods you defined.

  • Problems with Static and non-static stuff

    Right now I am trying to work on a RPG and trying to make it all using classes instead of having a Applet run everything and want to call Methods to make / remove the buttons here is the Method I'm dealing with
        public void placeButtons()
            attackBtn.setBounds(200,700,75,25);
            defendBtn.setBounds(200,725,75,25);
            magicBtn.setBounds(275,700,75,25);
            itemBtn.setBounds(275,725,75,25);
            game.add(attackBtn);   // Here is where I am having the problem (non-static method add(java.awt.Component) cannot be referenced from a static context)
            attackBtn.addActionListener(this);
        }Normally I would be making all my buttons in my main class but I want to know if I can make them in a separate class and load them in my main class so I can shorten my code by a ton.

    Generally speaking: Yes: you are only limited by your ingenuity and knowledge.
    //call from other class
    MyButtonClass mbc = new MyButtonClass();
    MyPanel p = new MyPanel();
    p.add(mbc.getMyMainButton());
    //what everAlthough I would think that it may be better to get your entire Frame back for display or a panel... It just seems like it's going to be awkward to work with unless you're making some kind of button generator or something, but then it's your app and from your description, the code given should illustrate a way of getting to the answer you seek.

  • SAP to Non-SAP Integration best Practices

    Hi Folks,
    Recently I demonstrated to few of my managers the integration of our SAP ISU with a 3rd Party MDUS System via SAP PI. A question which was repeatedly asked is 'Why SAP PI'? Isn't there any other way to do it? They did mention BAPIs and doing things directly in ABAP but I couldn't really answer as to how weigh one on the other in this particular scenario.
    I do know that there are standard ES Bundles for achieving integration with 3rd Party Systems via SAP PI, We can do the interface and message mappings but
    is it possible to achieve this integration with the 3rd Party MDUS System without using PI?
    3rd party MDUS can only integrate via its web Services so how would they get called?
    Whats the trade-off in case of Performance, Development Cost?
    I am looking for best practices, recommendations, trade-offs and possibilities. Your input is very much appreciated.
    Regards,
    Adil Khalil

    Hi Adil,
    The below blog might be useful
    Consuming Services with ABAP
    regards,
    Harish

  • Static or non-static...

    Well i guess this is a design issue...
    If i make an application, and create a main object for it like "App".
    Now i want the application to have some internal code for like maybe a network, and call it "Net".
    Now in the App, should i make the Net object static, and access it in a static way like Net.blalba. Doing so i could access the Net functions from anywhere in the application by just calling Net.things
    If it were not static, i would have to send along either the App reference or the Net reference to anything that should use it... Seems kind of exhausting...
    What is the GOOD way of doing this?

    OK, so its the static approach?
    Not sending around references to an object, but use it static instead?
    Now i have the "App" holding a static object of "Net" and in net we have a function called send(). Off course the net object is only made as one instance (singleton).
    So, whenever i wanna call the send() i do App.net.send(); From anywhere withing the program.
    Instead of sending the net object to any parts of the program that needs to access send...

  • How do I identify which is static and which is non static method?

    I have a question which is how can i justify which is static and which is non static method in a program? I need to explain why ? I think it the version 2 which is static. I can only said that it using using a reference. But am I correct or ?? Please advise....
    if I have the following :
    class Square
    private double side;
    public Square(double side)
    { this.side = side;
    public double findAreaVersion1()
    { return side * side;
    public double findAreaVersion2(Square sq)
    { return sq.side * sq.side;
    public void setSide(double s)
    { side = s;
    public double getSide()
    { return side;
    } //class Square
    Message was edited by:
    SummerCool

    I have a question which is how can i justify which is
    static and which is non static method in a program? I
    need to explain why ? I think it the version 2 which
    is static. I can only said that it using using a
    reference. But am I correct or ?? Please advise....If I am reading this correctly, that you think that your version 2 is a static method, then you are wrong and need to review your java textbook on static vs non-static functions and variables.

Maybe you are looking for

  • Built In application "YouTube" Is Way too slow!

    Hey guys, I'm new here btw, so hi to all. When i watch videos on youtube built in app IT TAKES FOREVER! to buffer the videos, I'm using WI-FI and my net connection is 20mb, I would love to use it but it just takes toooooo long to buffer it would take

  • Over Range Signal On Any Monitor

    I have a powermac G3 and I'm not sure what's wrong. It partly boots up but then it shows a folder with a ? And it keeps on flashing switching images with another folder with the finder face on it. What's wrong? And how do I fix it?

  • Conky and ROX --pinboard [solved]

    Right now my background is being set by ROX. I want Conky to be transparent, but it only shows up as a black background (the backround w/o ROX). How can I set Conky to be transparent to the ROX backbround?

  • Scanner calibration for colour-managed workflow

    I would like to do a decent calibration of my Epson V750 Pro scanner to achieve a colour-managed workflow. I have the latest version X-Rite i1 Photo Pro 2 calibration kit, and although this enables me to calibrate my monitor and printer, it does not

  • Unselected calenders in the notification center

    Dear Apple Community, I'm having a problem with my unselected calenders, which appear, even unselected in the notification center. Here is what I wrote (via iPhone feedback) to Apple: "Dear Apple, since iOS 5 (I hope it would be fixed with iOS 6, it