Search code examples
javamethodsstaticnon-static

"Non-static method cannot be referenced from static context" error


What I want to do is to add Objects from another class(Noten) here and to print them out. I know that this is a common problem but still I can't find a solution.

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

Solution

  • Change your for loop from

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

    To

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

    As noteInfo method is defined as non static method and you are trying to access it statically using Noten (class). You could only access it on objects which you already have reference stored in arraylist.