0

How to use getters and setters? Semi question: How to create structure to easily retrieve data?

After setting the data in setter I can't retrieve it from the getter.

The structure is as follows:

Interaction - parent class with getters and setters                                             
Dictionary, CategoryInteraction, WordsInteraction - subclasses 

Here is my code:

public class Dictionary extends Interaction {

    private String resource = "/home/kjlk/IdeaProjects/Jdf/src/fdf/res";
    private File resourceFile = new File(resource);
    private Scanner scanner;
    private LinkedHashMap<Integer, String> categories;

    public void getCategoriesFromDictionary() {
        Interaction interaction = new Interaction();
        try {
            scanner = new Scanner(resourceFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        categories = new LinkedHashMap<>();
        int categoriesCount = 1;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.startsWith("_")) {
                categories.put(categoriesCount, line);
                categoriesCount++;
            }
        }
        scanner.close();
        setCategories(categories);
    }
}

public class Interaction {

    private LinkedHashMap<Integer, String> categories;


    public LinkedHashMap<Integer, String> getCategories() {
        return categories;
    }

    public void setCategories(LinkedHashMap<Integer, String> categories) {
        this.categories = categories;
    }
}

public class CategoryInteraction extends Interaction {

    public void printCategories() {
        LinkedHashMap<Integer, String> categories = getCategories();
        for (Integer key : categories.keySet()) {
            System.out.println(key + ": " + categories.get(key));
        }
        System.out.println();
    }
}

I'm getting NullPointerException for:

LinkedHashMap<Integer, String> categories = getCategories();

Thank you in advance! Please do not refer me to answers for NPE! The idea points to the working structure.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
Sorel
  • 91
  • 6

1 Answers1

0

You need to initialize the categories. By default it has value null. That is the reason for your exception.

Raj
  • 707
  • 6
  • 23