Home > Software engineering >  what is wrong in this static factory method code
what is wrong in this static factory method code

Time:04-27

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

}

}

CodePudding user response:

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.

CodePudding user response:

An instance variable is initialized by its default value unless it is final accordingly 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.

  • Related