Background A scavenger hunt question from the assigned readi

Background: (A scavenger hunt question from the assigned readings.) Consider this Java code: class X { //a private int i; // b private X(){) // c static X factory(int v){ // d X r = new X(); // e r.i = v; // f return r; // g } // h ... other methods ... // i } // j If line c was deleted, is there a risk that code outside of class x could create an improperly initialized instance of x? Most Java compilers are not smart enough to figure out your answer to part a: as a consequence, they demand that you make a change to your program. What change? If the keyword static was omitted on line d, how could code outside of class x create a new instance of x? Assume that a program using the above code is completely debugged and that it works perfectly. Under these circumstances, would deleting the keyword private from line c but making no other changes have any effect on the correctness of the program?

Solution

By seeing the code in the question above, there is a pattern implemented here.

JAVA SINLETON PATTERN

To implement Singleton pattern, we have different approaches but the common concepts followed here are as below

-> There is a private constructor to restrict instantiation of the class from other classes

-> private static variable of the same class that is the only instance of the class

-> Public static method that returns the instance of the class. This is the only global access point to outer world.

a) If line c is deleted, then the class is not a singleton pattern, object can be created anytime from any other class when we require to use and the static function present in the class is executed at the time of class loading and instance is created even though client application might not be using it.

b)

class X {

private int i;

private X r = new X();

static X factory(int v){

r.i = v;

return r;

}

}

c) If static is omitted, then

X test = new X();

X a = test.factory(3);

d) Removing a private from line c will create object of X in any other class using

X a = new X();

and also, at the time of loading of the class, it will call a factory method, which will create an instance of X. If class is not called outside the class, the instantiated object will be of no use.

 Background: (A scavenger hunt question from the assigned readings.) Consider this Java code: class X { //a private int i; // b private X(){) // c static X fact

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site