-2

I've been recently working on rewriting my school assignments from C++ to Java, to which I'm still a beginner. I made this class:

package ThreeDimensionalController;

import ThreeDimensionalShape.*;
import java.util.Deque;

public class ThreeDimensionalController {
    private Deque<ThreeDimensionalShape> setOf3DShapes;
    public void displayVolume() {
        for( ThreeDimensionalShape s : setOf3DShapes) 
System.out.println(s.volume());
    }
    public void displayArea() {
        for (ThreeDimensionalShape s : setOf3DShapes) 
System.out.println(s.area());
    }
    public void add(ThreeDimensionalShape shape) {
        setOf3DShapes.push(shape);
    }
}

and the problem is with method called "add", it doesn't compile - NullPointerException and I do know why, but can't figure out how to deal with it. The ThreeDimensionalShape class is an abstract class, that is extended by 3 other classes called Cone, Cylinder and Cube. I wanted it to work like this:

threedimensionalcontroller.add(new Cone(...));

How do I fix it, so that it works?

@Edit: The NullPointerException is solved, thank you everyone!

2 Answers2

0

You have to initialize setOf3DShapes before you push the shape object. In ThreeDimensionalController you can create a constructor in order to initialize the setOf3DShapes.

public ThreeDimensionalController() {
       if(setOf3DShapes == null)
                setOf3DShapes = new LinkedList<String>();
 }
-1

First of all you have not initialized the variable setOf3DShapes. So you are getting error. You can initalize the variable using implementation classes - ArrayDeque, ConcurrentLinkedDeque, LinkedBlockingDeque, LinkedList. for eg.

Deque<ThreeDimensionalShape> setOf3DShapes = new LinkedList<String>(); 
Sujay Mohan
  • 933
  • 7
  • 14