Hello, I need some help modifying this java file to generate not one single obje
ID: 3709251 • Letter: H
Question
Hello, I need some help modifying this java file to generate not one single object, but a specified amount of objects like 10.
public class Singleton {
/** The reference to the unique instance of the class */
private static Singleton theSingleton;
/**
* <b>Private constructor</b><br />
* Instances of this class cannot be created directly by calling the constructor.
*/
private Singleton() {
System.out.println("Singleton constructor called ... ");
}
/** Overrides Object's toString() */
@Override
public String toString() {
return this.getClass().getName();
}
/**
* Accessor class method responsible for creating and maintaining an unique
* instance
*/
public static Singleton getSingleton() {
if (theSingleton == null) {
theSingleton = new Singleton();
}
return theSingleton;
}
}// end class
Explanation / Answer
I have changed the below code. Instead of creating one Singleton object it will now create an array of Singleton objects. The size of array can be user specified. If user does not specify the size then default is set to 10. I am doing this using default and prametrized constructor. Please let me know if you have any issues in this.
public class Singleton {
/** The reference to the unique instance of the class */
private static Singleton[] theSingleton;
/**
* <b>Private constructor</b><br />
* Instances of this class cannot be created directly by calling the
* constructor.
* creating n objects and forming an array of that
*/
private Singleton(int n) {
theSingleton = new Singleton[n];
System.out.println("Singleton constructor called ... ");
}
/**
* <b>Private constructor</b><br />
* Instances of this class cannot be created directly by calling the
* constructor.
* creating 10 objects and forming an array of that
*/
private Singleton() {
theSingleton = new Singleton[10];
System.out.println("Singleton constructor called ... ");
}
/** Overrides Object's toString() */
@Override
public String toString() {
return this.getClass().getName();
}
/**
* Accessor class method responsible for creating and maintaining an unique
* instance
*/
public static Singleton[] getSingletons() {
if (theSingleton == null) {
theSingleton = new Singleton[10];
}
return theSingleton;
}
}// end class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.