Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Sun as a Singleton - example
- class Sun {
- //STEP 2 - make class create instance of itself
- private static Sun instance = new Sun();
- private Sun() { //STEP 1 - make all constructors private
- }
- public String toString() {
- return "the sun";
- }
- //STEP 3 - provide a static getInstance method
- public static Sun getInstance() {
- return instance;
- }
- }
- public class SunTester {
- public static void main(String args[]) {
- //create object using static getInstance() method
- Sun sun1 = Sun.getInstance();
- Sun sun2 = Sun.getInstance();
- //call instance methods using object ref
- System.out.println(sun1.toString());
- //if both sun1 and sun2 object refs point to same object
- //this comparison will be true
- System.out.println(sun1 == sun2);
- //and object hashcode will be same also
- System.out.println(sun1.hashCode() + " = " +sun2.hashCode());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment