javaobjectstatic-factory

what is wrong in this static factory method code


I am trying to learn static factory methods and their advantages over constructors but my code is throwing an error that final String name is not assigned a value(name might no be initialized)

public class Main {
public final String name;
private final String email;
private final String country;

public Main(String name, String email, String country) {
    this.name = name;
    this.email = email;
    this.country = country;
}

public Main() {}

static Main createName(String name, String email) {
    return new Main(name, email, "Argentina");
}
public   static void main(String[] args) {
    Main obj = new Main();
    createName("vipin", "vipin.com");
    System.out.println("This is name: " + obj.name + "\n" + "This is email address: " + 
    obj.email + "\n" + "This is country: " + obj.country);

}

}


Solution

  • Change:

    Main obj = new Main();
    createName("vipin", "vipin.com");
    

    to:

    Main obj = createName("vipin", "vipin.com");
    

    and forget the no-parameter constructor which do not initialise correctly the fields.