java 不能从静态上下文中引用非静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5972764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:46:20  来源:igfitidea点击:

non-static method cannot be referenced from a static context

javastatic

提问by jason m

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.

我唯一改变的是加载的 URL。但这不会导致错误。

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

我想称我的函数为“ readPosiitons”。简单的解决方案,使其成为静态。真正的解决方案,我不确定。

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

采纳答案by duffymo

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

真正的解决方案?不要在main()方法中放那么多东西。那是给菜鸟的。

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

Java 是一种面向对象的语言。将逻辑放在与GarageComm类关联的方法中。 main()应该做的只是实例化一个实例并调用它的方法。

Change it like this:

像这样改变它:

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

回答by Thorbj?rn Ravn Andersen

This is a typical mindbender for new Java programmers.

对于新的 Java 程序员来说,这是一个典型的头脑风暴。

A staticmethod does not belong to an object. A non-staticmethod belongs to an object.

static方法不属于一个对象。非static方法属于对象。

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

您使用main-method 约定来启动您的程序,并且该方法必须是静态的。

The trick to get from a staticmethod to a non-staticmethod, 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.

static方法到非static方法的技巧是,您必须创建一个对象,以便您可以调用该对象上的方法。即new GarageComm().readPositions(...)。我只是认为您不必在这里,因此将 readPositions 也标记为静态会更简单。

回答by Jér?me Verstrynge

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.

创建 GarageComm 的实例也可以,但在 Java 中这是一种糟糕的编程习惯,因为该对象没有状态。

回答by Ernest Friedman-Hill

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 GarageCommhas no state of its own, there's no reason to create a GarageCommobject, so it's just as well you mark the method static, so no object is required to call it.

由于GarageComm没有自己的状态,因此没有理由创建GarageComm对象,因此将方法标记为静态也无妨,因此不需要任何对象来调用它。

回答by Nishant

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 maydepend 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 mightfail. So, it is a kind of prevention.

现在,如果我们允许静态方法与非静态方法(和非静态变量)一起使用,它们可能会失败。所以,这是一种预防。

When should I consider making a method static?

我什么时候应该考虑将方法设为静态?

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

现在,来,为什么不制作方法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.

更新:看起来这篇文章让一些人感到困惑,所以更新了答案。