what is wrong in this static factory method code

212 Views Asked by At

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);

}

}

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

An instance variable is initialized by its default value unless it is final when the object is instantiated. If you initialize it out of one of its constructors, it cannot be initialized in the constructor(s). So, advisedly, final instance variables should be initialized in constructors.