1

I'm having a problem in my abstract class and its subclass. ActionDeck is a subclass of Deck which contains a no-argument constructor for ActionDeck, but whenever I get NullPointerException for the deque and array list instance variables my superclass has. It also marks it as unused in VScode. I'm not sure if I am implementing it correctly. What is wrong with my code?

Deck.java

abstract class Deck<C> {

    protected Deque<C> deck;
    protected ArrayList<C> temp;
    
    public Deck () {
        Deque<C> deck = new ArrayDeque<>();
        ArrayList<C> temp = new ArrayList<>();  
    }

ActionDeck.java

public class ActionDeck extends Deck<ActionCard> {

    public ActionDeck() {
        super();
    }

So when I tried to add something into the arraylist in ActionDeck it spits out an error:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.ArrayList.add(Object)" because "this.temp" is null
        at ActionDeck.generateDeck(ActionDeck.java:26)
        at Board.initializeData(Board.java:30)
        at Main.main(Main.java:10)

Help would be appreciated, thank you!

sphynxo
  • 41
  • 2
  • 5

1 Answers1

0

The Deck constructor isn't initializing the members - it's declaring two local variables which hide the members and initializing them. Remove the type declarations on those lines, and you'll get the behavior you expected:

public Deck () {
    deck = new ArrayDeque<>();
    temp = new ArrayList<>();  
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350