scentless apprentice
scentless apprentice

Reputation: 105

Creating multiple objects using the same instance

I just saw this tutorial creating multiple objects using the same instance by applying the DAO pattern and tried it in a simple console, but I always get this message java.lang.NullPointerException I'm now confused, as far as I know, a constructor can be used once only, and the object will be immutable. Kindly look at this:

Fighter.java

public class Fighter {
    private String style;

    public Fighter() {}

    public String getStyle() {
        return style;
    }
    public void setStyle(String style) {
        this.style = style;
    }
}

FightersDAO.java

public class FightersDAO {
    public List<Fighter> getFighters(){

        List <Fighter> fighter = new ArrayList<>();
        String [] styles= { "Karate", "Sumo", "Pro-Wrestling" };

        for(int i=0; i < styles.length; i++) {
            Fighter temp = new Fighter();;
            temp.setStyle(styles[i]);
            fighter.add(temp);
        }
        return fighter;
    }
}

Demo.java

public class Demo {
    private static FightersDAO fighterDAO;
    public static void main (String [] args) {
        List <Fighter> fighters = fighterDAO.getFighters();

        for(Fighter e: fighters) {
            System.out.println(e.getStyle()); //this should output the objects, but nothing shows
        }
    }
}

Why is it null? What part did went wrong

Upvotes: 0

Views: 63

Answers (3)

akshay k.k
akshay k.k

Reputation: 133

In your code
private static FightersDAO fighterDAO;// here is not initialized. its just a declaration so fighterDAO = null;

while executing below code will throw exeption List fighters = fighterDAO.getFighters();// means null.getFighters();

Below is the correct code

package aks;

import java.util.List;

public class Demo { private static FightersDAO fighterDAO= new FightersDAO();

public static void main (String [] args) {
    List <Fighter> fighters = fighterDAO.getFighters();

    for(Fighter e: fighters) {
        System.out.println(e.getStyle()); 
    }
}

}

You can analyse this by just debuggin on eclise or any IDE

If you want same instance use below code

private static FightersDAO fighterDAO = new FightersDAO();

Upvotes: 0

yeahseol
yeahseol

Reputation: 385

private static FightersDAO fighterDAO;
I think there is a problem because it is not initialized.

Change it:
private static FightersDAO fighterDAO = new FightersDAO();

Upvotes: 3

Henry
Henry

Reputation: 43728

The variable fighterDAO is never initialized. Therefore you get a NPE here:

List <Fighter> fighters = fighterDAO.getFighters();

To fix that use:

private static FightersDAO fighterDAO = new FightersDAO();

Upvotes: 3

Related Questions