Search code examples
javagetter-setter

cant make a static reference to the non static method


i had a google for my issue and although i can find many questions with the same title, i cant seem to find a resolution that fits my example.

Library.java

public class Library {

public ArrayList<Book> books = new ArrayList<Book>();

public Library(){
      super();
    }

//Getters/Setters
public Library(ArrayList<Book> books) {
    this.books = books;
}

public ArrayList<Book> getBooks() {
    return books;
}

public void setBooks(ArrayList<Book> books) {
    this.books = books;
}

LibraryTester.java

import java.util.ArrayList;
import java.util.Scanner;

public class LibraryTester {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    ArrayList<Book> books = Library.getBooks(); //Getting error here
    books = Library.CreateBooksArrayList();
    MenuInput(sc, books);
    sc.close();
    Library.setBooks(books); //And here

}

Changing the getters/setters to static doesnt seem to work, im an absolute java noob so its probably some silly mistake, would anybody have any clue on how to access the getter/setter methods in the 'library' class from the 'library tester' class. Thanks in advance for any help


Solution

  • getBooks() is not a static method of Library class. You need to create an instance of a library then call the instance's method. (Also not sure what you're trying to accomplish with your main method when you query for the books list and then call setBooks to set it to the value you read...). Also would second the advice about reading a good tutorial or two.

    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class LibraryTester {
    
       public static void main(String[] args) {
    
        Scanner sc = new Scanner(System.in);
        Library lib = new Library();
        ArrayList<Book> books = lib.getBooks();
        MenuInput(sc, books);
        sc.close();
    }