Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question regaring Singleton.

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code below is a Singleton which means that only one instance of class Singleton can be created.
But I was able to create tho instances in class
Singleton_Test but the two instances hat the same
content regarding instance variable number which is 4 in bot instances.
Why is it possible to create two instances from class singleton and why do all singleton instances have the content of the last created Singleton instance?
Appreciate your answers.
Thomas

Result:
C:\Java\EigeneJavaProgramme>java Singleton_Test
3
44
 
Dave Landers
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You did not create two instances, only one.
You have two variables which reference the same singleton instance.
You can test that by checking that instance==instance1.
The reason they both have the same contents is because they are the same object.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...but if you really did want to (kinda) subvert the notion of static in Java, take a look at http://www.javageeks.com/Papers/JavaStatics/JavaStatics.pdf
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic