簡體   English   中英

無法從靜態上下文引用非靜態方法

[英]non-static method cannot be referenced from a static context

我想一勞永逸地理解這一點。

有了這個,請原諒下面粘貼的大量代碼,但我不想遺漏任何細節。

我唯一改變的是加載的URL。 但這不會導致錯誤。

我想把我的功能稱為“ readPosiitons ”。 簡單的解決方案,使其靜止。 真正的解決方案,我不確定。

請幫助我更好地了解如何以正確的方式解決此錯誤。

謝謝!!

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

真正的解決方 不要在main()方法中放入太多東西。 這是為了新手。

Java是一種面向對象的語言。 將邏輯放在與GarageComm類關聯的方法中。 main()應該只是實例化一個實例並調用它的方法。

像這樣改變它:

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

這是新Java程序員的典型思維導向器。

static方法不屬於對象。 static方法屬於對象。

您使用main -method約定來啟動程序,並且該方法必須是靜態的。

static方法到非static方法的技巧是,您必須創建一個對象,以便可以在其上調用該方法。 new GarageComm().readPositions(...) 我只是覺得你不必在這里,所以將readPositions標記為靜態也會更簡單。

你需要讓你的函數靜態:

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

創建GarageComm實例也會起作用,但這在Java中是不好的編程實踐,因為該對象沒有狀態。

在這種情況下,將方法設為靜態是一個好主意。 另一種方式是使用

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

代替。

那么,為什么這個錯誤呢?

靜態方法不能在同一個類中調用非靜態方法。 這聽起來很奇怪,但這是有道理的。 考慮一下:

  • 非靜態方法可能取決於對象的狀態,即實例變量。

  • 可以從外部調用靜態方法而無需實例化

現在,如果我們允許靜態方法使用非靜態方法(和非靜態變量),它們可能會失敗。 所以,這是一種預防。

我什么時候應該考慮使方法靜態?

現在,來, 為什么不讓方法static

很好,如果一個方法的功能不依賴於對象的狀態,你應該使方法成為靜態的。

如果它只是使用傳遞的參數和一些靜態的東西(靜態變量,靜態方法)和返回(有/沒有結果,拋出異常的東西),考慮使它成為靜態方法。


更新:看起來像這個帖子困惑了幾個人所以更新了答案。

如果方法不是靜態的,則必須在對象上“調用”它。 從非靜態方法調用方法時,隱含該對象 - 它是調用第一個方法的對象。 但是當從靜態方法調用它時,沒有隱含的對象,因此要調用該方法,您必須提供一個對象:

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

由於GarageComm沒有自己的狀態,因此沒有理由創建GarageComm對象,所以你也可以將方法標記為static,因此不需要任何對象來調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM