1

I'm newbie at java and have no idea how to repair my simple code. I need to create a person, using another class, in this case, "PersonBuilder". The problem is, that I've got NullPointerException :X

Exception in thread "main" java.lang.NullPointerException at RevStr$PersonBuilder.withAge(RevStr.java:64)
at RevStr.main(RevStr.java:75)

There is class Person

public class Person{
private String name;
private String surname;
private int age;
private String pesel;

// ** AKCESOR I MUTATOR ** //
public void setName(String name){
    this.name = name;
}
public void setSurname(String surname){
    this.surname = surname;
}
public void setAge(int age){
    this.age = age;
}
public void setPesel(String pesel){
    this.pesel = pesel;
}

public String getName(){
    return this.name;
}
public String getSurname(){
    return this.surname;
}
public int getAge(){
    return this.age;
}
public String getPesel(){
    return this.pesel;
}

}

and PersonBuilder

    public static class PersonBuilder{
    private Person p;

    public Person build(){
    return p;
    }

public PersonBuilder withName(String name){
    p.setName(name);
    return this;
}
public PersonBuilder withSurname(String surname){
    p.setSurname(surname);
    return this;
 }
public PersonBuilder withAge(int age){
    p.setAge(age);
    return this;
}
public PersonBuilder withPesel(String pesel){
    p.setPesel(pesel);
    return this;
}
}

Main method

public static void main(String[] args) {
Person p = new PersonBuilder().withAge(25).withName("A").withSurname("B").withPesel("11224").build();
System.out.println(p);
}

I assume that the problem could be repaired quickly and simply, but I can't see the solution right now :X

Cipozerca
  • 21
  • 1
  • 1
    You shouldn't have an instance of Person in that builder. The build() method should return one. In the builder, you should only have the same instance variables you have within the Person class itself – Stultuske Oct 09 '16 at 11:55
  • In your `withAge` method you have `p.setAge(age);` but `p` is declared as `private Person p;` field which as you see doesn't hold any specific `Person` instance. Instead since you didn't assign any value to that reference it is holding `null` (default value for class field which is reference variable). So you are ending calling `null.setAge` which is causing NPE. – Pshemo Oct 09 '16 at 11:58

0 Answers0