dsmishra1981
dsmishra1981

Reputation: 49

Factory Pattern Example in Java

I was trying one example in factory pattern. This is giving me ArrayIndexOutOfBoundsException. Could someone explain ?

java.lang.ArrayIndexOutOfBoundsException: 0 at com.factory.SalutationFactory.main(SalutationFactory.java:10) 

Here are my classes.

package com.factory;

public class SalutationFactory {

    public static void main(String[] args) {

        try
        {
        SalutationFactory factory = new SalutationFactory();        
        factory.getPerson(args[0], args[1]);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public Person getPerson(String name, String gender){

        if(gender.equals("M"))
            return new Male(name);
        else if(gender.equals("F"))
            return new Female(name);
        else 
            return null;
    }
}

package com.factory;

public class Person {

    private String name;
    private String gender;

    public String getName(){
        return name;
    }

    public String getGender(){
        return gender;
    }

}

package com.factory;

public class Female extends Person {

    public Female(String fullname){
        System.out.println("Hello Ms " + fullname);
    }
}

package com.factory;

public class Male extends Person {

    public Male(String fullname){
        System.out.println("Hello Mr " + fullname);
    }

}

Thanks Dev

Upvotes: 2

Views: 7039

Answers (4)

Naeem Iqbal
Naeem Iqbal

Reputation: 405

You must check for null or objects before just using them. Just add the line

if (args.length >= 2)
    factory.getPerson(args[0], args[1]);
/* else 
    Add reminder to provide at least 2 arguments. */

Upvotes: 0

GiorgoCH
GiorgoCH

Reputation: 194

I have try the same example and after trying here is the solution.Create this code.

String []pin =new String[4];
    pin[0]="M";
    pin[1]="F";
    Factory factory = new Factory();
    factory.getPerson(pin[0],pin[1]);

this will work

and your out put should be "female".

Upvotes: 0

Chandra Sekhar
Chandra Sekhar

Reputation: 19500

factory.getPerson(args[0], args[1]);

Here you are using command line argument, so while running this applicatio you have to pass the command line argument

run using

java SolutionFactory Santosh M

Here Santosh will be assigned to args[0] and M will be assigned to args[1]

If without passing any command line argument, you run this program, then length of args will be zero and inside main() you are calling args[0] which causes ArrayIndexOutOfBounds exception

Upvotes: 2

Brian Agnew
Brian Agnew

Reputation: 272427

Since this is the only line using arrays:

 factory.getPerson(args[0], args[1]);

I suspect you're not providing 2 command-line args. You'll need something like:

$ java com.factory.SalutationFactory Smith M

Upvotes: 4

Related Questions