簡體   English   中英

“無法從靜態上下文引用非靜態方法”錯誤

[英]“Non-static method cannot be referenced from static context” error

我想要做的是在這里添加另一個類( Noten )中的對象並打印出來。 我知道這是一個普遍的問題,但仍然找不到解決方案。

private ArrayList<Noten> notes123;
public void addNotes(Noten newNotes) {
    if (notes123.size() >= 0) {
        notes123.add(newNotes);
        System.out.println(newNotes);
    } else {
        System.out.println("No Notes.");
    }
}
public void schuelerInfo() {
    System.out.println("Name: " + name + " Student number: " + nummer);
    System.out.println("The notes are ");
    for (Noten note: notes123) {
        System.out.println(Noten.notenInfo());
    }
}

從更改您的for循環

for (Noten note : notes123){
   System.out.println(Noten.notenInfo());
}

for (Noten note : notes123){
   note.notenInfo();
}

由於noteInfo方法被定義為非靜態方法,因此您嘗試使用Noten(類)靜態訪問它。 您只能在已將引用存儲在arraylist中的對象上訪問它。

由於notenInfo()不是靜態方法,因此必須在Noten對象的實例上調用它。 例如:

Noten n = new Noten();
n.notenInfo();

暫無
暫無

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

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