In: Computer Science
Question 1 5 Marks
This question relates to the following class
public class QuestionX {
private static QuestionX quest = new QuestionX();
private QuestionX(){
}
public static QuestionX getQuestion() {
return quest;
}
public void doSomething(){
System.out.println("In doSomething");
}
//other methods for this class to do things
}
Here are the answers for your questions in Java Programming Language.
Kindly upvote if you find the answer helpful.
####################################################################
(a) How is this class used by a client? Provide code showing how you would use this class in the main method of a program.
Answer : In the given class QuestionX, a private static variable which holds class object is declared. Its constructor is in private mode. Hence,an object of the class using constructor cannot be created but only single object can be created using the static method getQuestionX. To further use the methods in the class we have to first get the static object of QuestionX using the static method getQuestionX.
Only one object can be created and used for this class.
CODE :
Below code demonstrates how to use QuestionX using main method by client.
QuestionX.java
public class QuestionX { private static QuestionX quest = new QuestionX(); private QuestionX(){ } public static QuestionX getQuestion() { return quest; } public void doSomething(){ System.out.println("In doSomething"); } } |
####################################################
QuestionTest.java (with main method)
public class QuestionXTest { public static void main(String[] args){ //Get the static object 'quest' from static method getQuestionX() QuestionX obj = QuestionX.getQuestion(); //Call member functions of the class using the static object. obj.doSomething(); } } |
#################################################################
SCREENSHOTS :
Please see the screenshots of the code below for the indentations of the code.
QuestionX.java
QuestionXTest.java
################################################################
OUTPUT :
###################################################################
(b) What constraints are placed on class usage by the above implementation? Explain how this has been achieved.
Answer :
Constraints on above class usage :
Explanation : We cannot use this class like we normally use other classes in Java. We cannot create multiple intances of the class since the class has private constructor, but can create only one static instance and use it to access class' public member variables/methods.
This is how we can work on the class inspite of the constraints of the implementation.
###########################################################################
Any doubts regarding this can be explained with pleasure :)