jason m
jason m

Reputation: 6835

non-static method cannot be referenced from a static context

I would like to understand this once and for all.

With this please excuse the mass of code pasted below, but I do not want to leave out any details.

The only thing I changed is the URL loaded. But this is not causing the error.

I would like to call my function "readPosiitons". Easy solution, make it static. Real solution, I am not sure of.

Please help me to better understand how to solve this error in the correct way.

Thanks!!

            /*
             * To change this template, choose Tools | Templates
             * and open the template in the editor.
             */

            package PandL;

            import java.io.BufferedReader;
            import java.io.File;
            import java.io.IOException;
            import java.io.InputStreamReader;
            import java.net.MalformedURLException;
            import java.net.URL;
            import java.util.HashMap;
            import java.util.Scanner;
            import toolBox.Secretary;
            import toolBox.Secretary.positionObj;

            /**
             *
             * @author Jason
             *
             */
            public class GarageComm {
                public static void main(String[] args) throws MalformedURLException, IOException{
                    String retStr;
                    String startM;
                    String endM;
                    String myURL;
                    String[] Split1=null;
                    Integer lnCount;
                    HashMap hashPos=new HashMap();
                    hashPos= readPositions("holdingsBU.txt");//the error is here

                    myURL="http://myUrl?s=";

                    URL url = new URL(myURL);
                    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));



                    in.close();
                }

                public HashMap readPositions(String destFile){

                    HashMap<String, Secretary.positionObj> hashPositions=new HashMap<String,positionObj>();
                    Secretary mySecretary=new Secretary();
                    try{
                        File F=new File(destFile);
                        if(F.exists()){
                            System.out.println("File Exists: "+F.exists());
                            System.out.println(destFile);
                            Scanner sC= new Scanner(F);

                            while (sC.hasNext()){
                                String[] Splitter1;
                                Secretary.positionObj position=mySecretary.new positionObj();


                                Splitter1=sC.nextLine().split(",");
                                position.positionDate=Double.parseDouble(Splitter1[0]);
                                position.positionTicker=(Splitter1[1]);
                                position.positionOpen=Double.parseDouble(Splitter1[2]);
                                position.positionPrice=Double.parseDouble(Splitter1[3]);
                                position.positionSMA=Double.parseDouble(Splitter1[4]);
                                position.positionUpdated=Double.parseDouble(Splitter1[5]);
                                position.priceUpdated=Double.parseDouble(Splitter1[6]);
                                position.updateDate=Double.parseDouble(Splitter1[7]);


                                hashPositions.put(position.positionTicker.trim(), position);

                            }


                        }else{
                            System.out.println("File Created: "+ F.createNewFile());
                            System.out.println("----No previous positions----");
                        }

                    }catch (Exception E){
                        System.err.println(destFile + " does not exist.");
                        hashPositions.put("ERROR", null);
                        E.printStackTrace();
                    }
                    return hashPositions;
                }
            }

Upvotes: 3

Views: 21790

Answers (5)

Nishant
Nishant

Reputation: 55866

It's a good idea in this case to make the method static. The other way is to use

  new GarageComm().readPositions("holdingsBU.txt")

instead.

So, why this error?

A static method can not call a non-static method in the same class. It sounds bizarre, but there is a reason for it. Consider this:

  • Non static methods may depend on the state of the objects, the instance variable to say.

  • Static methods can be called from out-side without instanciating

Now, if we allow static methods to play with non-static method (and non static variables), they might fail. So, it is a kind of prevention.

When should I consider making a method static?

Now, come to, why not make the method static?,

Very well, you should make a method static if it's functionality does not depend on the object's state.

If it just uses the passed parameters and some static stuffs (static variable, static methods) and returns (with/without a result, throwing exception anything), consider making it static method.


update: looked like this post confused a couple of people so updated the answer.

Upvotes: 0

This is a typical mindbender for new Java programmers.

A static method does not belong to an object. A non-static method belongs to an object.

You use the main-method convention to have your program started, and it is required that that method must be static.

The trick to get from a static method to a non-static method, is that you must create an object so you can call the method on that. I.e. new GarageComm().readPositions(...). I just don't think you have to here, so it would be simpler to just mark readPositions as static too.

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

If a method is not static, then it must be called "on" an object. When calling a method from a non-static method, that object is implied -- it's the object the first method was called on. But when calling it from a static method, there is no implied object, so to call the method, you must supply an object:

GarageComm gc = new GarageComm();
hashPos= gc.readPositions("holdingsBU.txt");

Since GarageComm has no state of its own, there's no reason to create a GarageComm object, so it's just as well you mark the method static, so no object is required to call it.

Upvotes: 0

duffymo
duffymo

Reputation: 308998

Real solution? Don't put so much stuff in the main() method. That's for noobs.

Java's an object-oriented language. Put the logic inside methods associated with the GarageComm class. main() should do little more than instantiate an instance and call its methods.

Change it like this:

            GarageComm gc = new GarageComm();
            hashPos= gc.readPositions("holdingsBU.txt");//the error is here

Upvotes: 2

You need to make your function static:

public static HashMap readPositions(String destFile) {
...
}

Creating an instance of GarageComm would work too, but this is bad programming practice in Java, since that object has no state.

Upvotes: 1

Related Questions