Write a program named ChopstickDemo.java, which has two classes Chopstick and Ch
ID: 3600184 • Letter: W
Question
Write a program named ChopstickDemo.java, which has two classes Chopstick and ChopstickDemo. The Chopstick class has a field name (a String) and a few other members:
A private constructor that takes a String as the argument and assigns it to name.
An overridden toString() method that returns name.
Two private static variables cs1 and cs2, and they are initialized with names “Chopstick1” and “Chopstick2”.
Two methods access1() and access2(), which return the two static members, respectively.
The ChopstickDemo class only has a main method that prints out the above two static members of Chopstick.
Hint: There’s a similar example in the lecture slides. It was called “singleton” because only one object was allowed to be created. Here two (and only two) Chopstick objects are allowed to be created.
The program should work like below:
java ChopstickDemo
>Chopstick1
>Chopstick2
Explanation / Answer
Hi..Please check below code.
Chopstick .java
public class Chopstick {
private String name;
private Chopstick(String name){
this.name=name;
}
public String toString() {
return "Chopstick [name=" + name + "]";
}
private static String cs1="Chopstick1";
private static String cs2="Chopstick2";
public static String access1(){
return cs1;
}
public static String access2(){
return cs2;
}
}
ChopstickDemo.java
public class ChopstickDemo {
public static void main(String args[]){
//Chopstick c = new Chopstick("hello");
System.out.println(Chopstick.access1());
System.out.println(Chopstick.access2());
}
}
Output:
Chopstick1
Chopstick2
If we creating object for Chopstick there was problem like constructor we are defined as private so java didnt allow to create object for private constructors. So i have named static methods and access the static methods from any class with classname.staticmethod name and the method access specifier also public only.
Thank you. All the best.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.