A factory method is a method that like a constructor initial
Solution
Hi buddy, please go through java program. I\'ve added comments for your better understanding
import java.util.*;
import java.lang.*;
import java.io.*;
class MyClass{
private Field f; //Guaranteed to be not null
//Constructors
private MyClass(){}; // prevent public use of default constructor
MyClass (Field p){
///This condition checks whether the field is null or not
if(p!=null){
f = p;
}
}
//factory
static MyClass Factor(Field p){
//Create an object only if p is not null
if(p!=null){
MyClass m = new MyClass();
m.f = p;
return m;
}
//Do not create object and return null if p is null
return null;
}
}
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
}
1. In the first approach , we can check if the field is not null. But we can\'t prevent the case of f being null
for the new object.
2. In the second approach , we can check if the field is not null and then create and return object
This serves our purpose and we can return null if the field passed is null. Thus we can prevent
creation of object when a null is passed
