Search code examples
javanullpointerexceptionencapsulation

Prevent NPE: accessing private object from another class


I've declared a private variable in one class that I want to access in another. But the problem is that when I pass the object flappyBird, it is null. What change do I need to make, so that it isn't?

FlappyBird.java : object created here

public class FlappyBird implements ActionListener, KeyListener, MouseListener
{

    private static FlappyBird flappyBird;

    public static void main(String[] args)
        /* CREATE INSTANCE OF FLAPPBIRD() */
    {
        flappyBird = new FlappyBird();
    }

    public static FlappyBird getBird() {
        return flappyBird;
    }

    public static void paint(Graphics phics) {
        ...
    }

GraphicRenderer.java : access object here

    public class GraphicsRenderer extends JPanel
    {
        private static FlappyBird bird = new FlappyBird();

    public void paint(Graphics phics)
    {
        // Generate game graphics by calling paint() in FlappyBird.
        bird.getBird();
        super.paint(phics); 
        bird.paint(phics);
    }
}

Solution

  • Your classes are very wrong. There is not a getter and many parts don't make sense. Here is a list of what's wrong with the code:

    • No setter so the field would always be null

    • For some reason, a field for instantiation

    • You don't implement the methods from the interfaces you implement. I will not fix that here but you implement it yourself

    • FlappyBird class has no method paint(). I also won't address this hear because you can do that yourself and you don't provide any details regarding the method

    Here are some fixes:

    public class FlappyBird implements ActionListener, KeyListener, MouseListener {
    
        private static FlappyBird flappyBird;
    
        public FlappyBird(/* Some attributes to the bird */) {
            /* Field = attribute */
        }
    
        public static void main(String[] args) {
            flappyBird = new FlappyBird(/* Constructor Args */);
        }
    
        public FlappyBird getBird() {
            return flappyBird;
        }
    
        public void setBird(/* You decide the arguments */) {
            /* Field = argument */
        }
    }
    

    I added a constructor, fixed the above code, added a setter. The constructor is called like this:

    FlappyBird fb = new FlappyBird(arguments);
    

    Now, when calling, you need to instantiate and call constructor. Then, you can access the methods. I stored the getBird() return value in b and fb as an instance. You can extend off this code.

    public class GraphicsRenderer extends JPanel {
    
        public void paint(Graphics phics) {
            FlappyBird fb = new FlappyBird(/*Args*/);
            FlappyBird b = fb.getBird();
            fb.setBird(/*Args*/);
        }
    }