A factory method is a method that like a constructor initial

A factory method is a method that, like a constructor (initializer) returns a newly built instance of a class. Consider this example: class MyClass {private Field f;//guaranteed to be non null//constructors private MyClass() {}//prevent public use of default constructor MyClass(field p) {//Bug: missing code to prevent p == null f = p;}//factory static MyClass factory(Field p) {My class m = new MyClass{);//Bug: missing code to prevent p == null m.f = p; return m;}} Note that, as written above, MyClass(x) and MyClass. factory(x) do exactly the same thing. The options for assuring that the parameter is not null are different, leading to potential different behaviors. In the constructor, what can you do to detect and prevent MyClass (null)? In the factory, what can you do to detect and prevent MyCass.factory(null)? (Suggestion: If some of the alternatives are the same as in part a, say so and focus on the differences.)

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

 A factory method is a method that, like a constructor (initializer) returns a newly built instance of a class. Consider this example: class MyClass {private Fi

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site