Static VS Private constructor in singleton
Dear All
Can u tell me waht is the basic adiffernce B/w static methpd call and singleton pattern.
Even in bothe the case we carete only one ibstance.
For me, I like to use singleton when I need to
perform some things inside the constructor. Butthere
is other reason, more important: if one day youneed
to modify to a "simple class patern", that is,
with
a
simple constructor, this maintenance will be
relativelly easy if you use singleton.And again, to me, none of this makes any sense.How
is maintenance eased by placing code in a
constructor? Why not in the static facade? Whynot
in a static initializer? They are all equally'easy'
IMO.
suppose the following static method, that is using
the static method of TheClass:
public static void method() {
TheClass.staticMethod();
}Now you have to change, that is, the class now has to
be a class with more than one instance, because of
the change in the business rule of your system.
Therefore, not only one instance anymore will be
used. The maintenance of your system will be more
complicated, doesn�t it? See below:
private TheClass objClass;
public static void method() {
//ooops, it won�t compile
objClass.staticMethod();
}If you develop your system based on singleton
pattern, you will be more prepared for this kind of
maintenance.
Of course, there are other solutions for this unlucky
situation. Actually, this problem occur when you are
developing a system, and the business rules are not
so definitive yet, so changes in these rules are
happening with a relative frequency. I am just saying
a probably unlucky situation that might happen.I fail to see how you can do anything but alter the class and its dependencies if the requirements change. Is this not always the case? How does having a static method (or a Singleton) obviate the issue any more over any other type of class, or even switching between the types?
How does making the object a Singleton 'prepare' me for change? In your mind, the dot-notation may be convenient over writing 'new', but other than that, I can't see how.
- Saish
Similar Messages
-
Initiating variables with private constructor fails
Goodday all,
At the moment I'm working on a little class that reads the input from the console screen. The class looks like this (I omitted a few unrelevant methods):
public class SomeClass {
private static BufferedReader bin = null;
// private constructor; another method (not shown here) returns an instance
private SomeClass() {
bin = new BufferedReader(new InputStreamReader(System.in));//somehow this doesn't work ??????
//public method
public final String readLine(String message) {
String feedback = "";
try {
if(bin==null) say("variable bin is null"); //bin is indeed null, just don't know why
else feedback = bin.readLine();
catch (IOException e) {
e.printStackTrace();
return feedback;
}Executing this code will result in output "variable bin is null". When I try debugging it, I see that the variable bin will remain null when the constructor is called.
Placing the initiation of 'bin' in another method will make things work, but I want to know why it doesn't work in the constructor. It seems as a fair piece of code ;).private static BufferedReader bin = null;Why is it static?
// private constructor; another method (not shown here) returns an instance
private SomeClass() {
bin = new BufferedReader(new InputStreamReader(System.in));//somehow this doesn't work ??????
}'Somehow it fails?' It doesn't even compile!
Executing this code will result in output "variable bin is null". When I try debugging it, I see that the variable bin will remain null when the constructor is called.Your constructor doesn't even compile, so I find it hard to believe it ever executed. -
Can java have Protected or Private Constructor
Hi,
can java have Priavte or protected constructor,
as we know java have default and public constructor ,
and in using singleton design patters we can use private & protected constructor,
so, what is the main logic,
Regards,
PrabhatHi,
Yes, We can declare constructor as private/public/protected also.
Having only private constructors means that you can't instantiate the class from outside the class (although instances could still be created from within the class - more about this later). However, when you instantiate a class, you must first initialize all superclasses of that class by invoking their constructors. If one of the superclasses has only private constructors declared, we have a problem. We can't invoke the superclass' constructor which means that we can't instantiate our object. Because of this, we've essentially made a class that can't be extended.
example:
class TheWorld
private static TheWorld _instance = null;
private TheWorld() {}
public static TheWorld instance()
if ( _instance == null )
_instance = new TheWorld();
return _instance;
public void spin() {...}
public class WorldUser
public static void main(String[] args)
TheWorld.instance().spin();
} -
How to access the private constructor??
i have a one private constructor in which i define some important variables then how should i access that private constructor?(Is this related to singleton class? if possible give me some example )
Hi
you can access to your private constructor through static methods of that class.
you can create objects of that class using these static method.
example code
public class rrr
public static void main(String[] args)
a ao=a.getobj(30);
System.out.println(a.geti(ao));
class a
private int i;
private a(int x)
i=x;
static a getobj(int y)
return new a(y);
static int geti(a temp)
return temp.i;
enjoy .........
This is my first reply to forum .
If you found any problem free feel to tell
Thank you -
Why can't classes with private constructors be subclassed?
Why can't classes with private constructors be subclassed?
I know specifying a private nullary constructor means you dont want the class to be instantiated or the class is a factory or a singleton pattern. I know the workaround is to just wrap all the methods of the intended superclass, but that just seems less wizardly.
Example:
I really, really want to be able to subclass java.util.Arrays, like so:
package com.tassajara.util;
import java.util.LinkedList;
import java.util.List;
public class Arrays extends java.util.Arrays {
public static List asList(boolean[] array) {
List result = new LinkedList();
for (int i = 0; i < array.length; i++)
result.add(new Boolean(array));
return result;
public static List asList( char[] array) {
List result = new LinkedList();
for (int i = 0; i < array.length; i++)
result.add(new Character(array[i]));
return result;
public static List asList( byte[] array) {
List result = new LinkedList();
for (int i = 0; i < array.length; i++)
result.add(new Byte(array[i]));
return result;
public static List asList( short[] array) {
List result = new LinkedList();
for (int i = 0; i < array.length; i++)
result.add(new Short(array[i]));
return result;
public static List asList( int[] array) {
List result = new LinkedList();
for (int i = 0; i < array.length; i++)
result.add(new Integer(array[i]));
return result;
public static List asList( long[] array) {
List result = new LinkedList();
for (int i = 0; i < array.length; i++)
result.add(new Long(array[i]));
return result;
public static List asList( float[] array) {
List result = new LinkedList();
for (int i = 0; i < array.length; i++)
result.add(new Float(array[i]));
return result;
public static List asList( double[] array) {
List result = new LinkedList();
for (int i = 0; i < array.length; i++)
result.add(new Double(array[i]));
return result;
// Now that we extend java.util.Arrays this method is not needed.
// /**JCF already does this so just wrap their implementation
// public static List asList(Object[] array) {
// return java.util.Arrays.asList(array);
public static List asList(Object object) {
List result;
Class type = object.getClass().getComponentType();
if (type != null && type.isPrimitive()) {
if (type == Boolean.TYPE)
result = asList((boolean[])object);
else if (type == Character.TYPE)
result = asList(( char[])object);
else if (type == Byte.TYPE)
result = asList(( byte[])object);
else if (type == Short.TYPE)
result = asList(( short[])object);
else if (type == Integer.TYPE)
result = asList(( int[])object);
else if (type == Long.TYPE)
result = asList(( long[])object);
else if (type == Float.TYPE)
result = asList(( float[])object);
else if (type == Double.TYPE)
result = asList(( double[])object);
} else {
result = java.util.Arrays.asList((Object[])object);
return result;
I do not intend to instantiate com.tassajara.util.Arrays as all my methods are static just like java.util.Arrays. You can see where I started to wrap asList(Object[] o). I could continue and wrap all of java.util.Arrays methods, but thats annoying and much less elegant.Why can't classes with private constructors be
subclassed?Because the subclass can't access the superclass constructor.
I really, really want to be able to subclass
java.util.Arrays, like so:Why? It only contains static methods, so why don't you just create a separate class?
I do not intend to instantiate
com.tassajara.util.Arrays as all my methods are static
just like java.util.Arrays. You can see where I
started to wrap asList(Object[] o). I could continue
and wrap all of java.util.Arrays methods, but thats
annoying and much less elegant.There's no need to duplicate all the methods - just call them when you want to use them.
It really does sound like you're barking up the wrong tree here. I can see no good reason to want to subclass java.util.Arrays. Could you could explain why you want to do that? - perhaps you are misunderstanding static methods.
Precisely as you said, if they didn't want me to
subclass it they would have declared it final.Classes with no non-private constructors are implicitly final.
But they didn't. There has to be a way for an API
developer to indicate that a class is merely not to be
instantiated, and not both uninstantiable and
unextendable.There is - declare it abstract. Since that isn't what was done here, I would assume the writers don't want you to be able to subclass java.util.Arrays -
Private Constructors and Inheritance
Hi,
I have created a class according to the Singleton pattern, with a private constructor to prevent the public creation of class instances. Now I'd like to sub-class the Singleton, but I get errors saying the Singleton constructor is not visible. I guess this is caused by the privateness of the constructor, but I don't know if changing it to protected would ruin the Singleton pattern. Is there a good way to sub-class a Singleton?public class SingletonBase {
private static SingletonBase instance;
protected SingletonBase() throws InstantiationException {
synchronized (SingletonBase.class) {
if (instance != null)
throw new InstantiationException("single instance already exists");
else
instance = this;
public static SingletonBase getInstance() {
return instance;
} -
Private inner class with private constructor
I read that if constructor is public then you need a static method to create the object of that class.
But in the following scenario why I am able to get the object of PrivateStuff whereas it has private constructor.
I am messing with this concept.
public class Test {
public static void main(String[] args) {
Test t = new Test();
PrivateStuff p = t.new PrivateStuff();
private class PrivateStuff{
private PrivateStuff(){
System.out.println("You stuff is very private");
}A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
* Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.1]
Your main method is within the body of the top level class, so the type (the inner class) and method are accessible.
eg:
class ImInTheSameSourceFileAsInnerAccessTest {
public static void main(String[] args) {
InnerAccessTest t = new InnerAccessTest();
InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
public class InnerAccessTest {
public static void main(String[] args) {
InnerAccessTest t = new InnerAccessTest();
PrivateStuff p = t.new PrivateStuff();
private class PrivateStuff{
private PrivateStuff(){
System.out.println("You stuff is very private");
}Result:
$ javac -d bin src/InnerAccessTest.java
src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
^
src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
^
2 errors
Edited by: pm_kirkham on 20-Jan-2009 10:54 added example of 'in the same source file' -
Private constructor documented as public by javadoc
I'm generating document for a class similar to the following:
public class Example {
public static final Example TYPE1 = new Example();
public static final Example TYPE2 = new Example();
private Example() {
// private constructor
When I run the Javadoc tool on this class, it lists the constructor as being public, which it is not! Is this a bug in javadoc, or am I doing something wrong?I think I can explain it.
I would bet you first created the class without any constructor
and ran Javadoc on it.
In that case, not only does javac create a public default
no-arg constructor, but javadoc also documents that constructor,
even though it's not present in the source file.
Later, when you added the private constructor, that prevented
the default constructor from being automatically created.
This is documented at:
http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#16823
BTW, we consider relying on default constructors as poor programming
practice, as described at:
http://java.sun.com/j2se/javadoc/writingdoccomments/index.html#defaultconstructors
-Doug Kramer
Javadoc team -
Instantiate class with a private constructor
How do you call a class that happens to have a private constructor. how would one instantiate such a class? Generally constructors are supposed to be public.
But in many cases the constructor for a class can be private, so how to call such a class?khurrumnas wrote:
I dont think you would need to provide such a method (newInstance()), its there for you already in Class Class, so its suffice to just call
newInstance() to get an instance of class that happens to have a private constructor, in the simplest case.False, as jverd rightly mentioned. Example: public class Foo {
public static void main(String[] args) {
Exception expectedException = null;
try {
Bar b = (Bar) Class.forName("Bar").newInstance(); // throws Exception
} catch (Exception e) {
expectedException = e;
assert expectedException instanceof IllegalAccessException;
class Bar {
private Bar() {}
}As mentioned several times now, one can get around this restriction, but it's considered poor form to do so.
~ -
Getting Private Constructor of a Class
Hello all,
Is there any way to get the private constructor as we get the public constructors using Class.getConstructors() ?
getConstructors() method is not returning the private constructors, but I need the info about the private constructors also....so if it is possible, please let me know...
Thankstullio0106 wrote:
I know, however it's also impossible to invoke private methods but, using reflection, You can.That's a complete different thing. If the private method is not static, it is invoked on the current instance.
Is it also possible to use private constructors in the same way.
The problem I'm facing is to create a new instance of a class which extends another class and I need to use a private constructor of the superclass (I've no sources of that superclass).First, the Constructor of a class has to invoke a Constructor of a superclass as the first operation (either implicitely invoking an empty constructor or explicitely). There is no way to do any other operation before that. Second, a reflectively fetched Constructor instance always only can create instances of the class it is defined at (using newInstance()). So, yes, you could get access to a private Constructor. With that, you may be able to create a new instance of the class it is defined for. But that's about it. -
Can a object created using static keyword be recreated? Singleton Pattern
Hi All
To implement a Singleton I can use the following code
public Singleton {
private Singleton(){
private static final s_instance = new Singleton();
public Singleton getInstance(){
return s_instance;
Now if the Class Singleton gets unloaded during a program execution and again get loaded won't s_instance be recreated? If my question is correct this would lead to be leading to a new Singleton class instance with all the original variables.
Having answered the above question if I lazily initialize my Singleton using the following code won't the above problem still occur.
public Singleton {
private Singleton(){}
private final volatile Singleton s_instance = null;
public Singleton () {
if(s_instance != null) {
synchronized (s_instance) {
s_instance = new Singleton();
return s_instance;
Having answered all the above questions what is the best way to write a Singleton?Would the class get unloaded even if the Singleton object has some valid/reachable references pointing to it?
On a different note, will all the objects/instances of a class get destroyed if the class gets unloaded.That's the other way round, really: instances cannot be garbage-collected as long as they are strongly reachable (at least one reference pointing to them), and classes cannot be unloaded as long as such an instance exists.
To support tschodt's point, see the JVM specifications: http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#32202
*2.17.8 Unloading of Classes and Interfaces*
A class or interface may be unloaded if and only if its class loader is unreachable. The bootstrap class loader is always reachable; as a result, system classes may never be unloaded.
Will the same case (Custom ClassLoader getting unloaded) occur if I write the singleton using the code wherein we lazily initialize the Singleton (and actually create a Singleton instance rather than it being a Class/static variable).You should check the meaning of this vocabulary ("object", "instance", "reference"): http://download.oracle.com/javase/tutorial/java/javaOO/summaryclasses.html
The difference between the lazy vs eager initializations is the time when an instance is created. Once it is created, it will not be garbage collected as long as it is reachable.
Now I'm wondering, whether being referenced by a static attribute of a class guarantees being reachabe. I'm afraid not (see the JLS definition of reachable: http://java.sun.com/docs/books/jls/third_edition/html/execution.html#44762). That is, again, unless the class has been loaded by the system class loader. -
Class with private constructor can be extended or not
Hi All,
I have a doubt.
if a class has private constructor and there are some methods in this class.Can this class be extended and if yes how can we call its method in subclass?
Thanks
SumitKaranjit wrote:
If a class contains only private constructors, then it cannot be extended.Err... not the whole story!
public class Sabre20090603a
static class Fred extends Sabre20090603a
Fred()
super();
private Sabre20090603a()
} -
Final class and private constructor
Whats the difference in a final class and a class with private constructot?
If we can make a class non-extendable by just giving private constructor then whats the advantage of final class? (I know final is very useful for many other things but just want to get info in this contaxt)You can extend a class with a private constructor,I'm not sure about that. The compiler will complain.
KajThat depends on the signature of the private constructor.
If it's the no-arg constructor and you don't declare another constructor which you explicitly call from your derived class you will indeed get an error.
If however you never call it (and there's no way it can implicitly get called) from a derived class there should be no problem.
class Private1 {
private int q;
private Private1() {
public Private1(int i) {
q = i;
public void print() {
System.out.println(q);
public class Public1 extends Private1 {
public Public1() {
super(1);
public static void main(String[] args) {
new Public1().print();
}for example compiles and runs perfectly.
But remove the call "super(1);" from the constructor and it will fail to compile. -
Why is it that AS3 does not support private constructors as AS2 does?
Why is it that AS3 does not support private constructors as
AS2 does?
Private constructors are standard in most OOP languages (for
example
C++ and Java) and were supported in Actionscript 2. However,
this is
not the case in AS3 which only allows its constructors to
have the
'public' access modifier.
I have legacy code that I hope to migrate to the AS3
platform. Some
key elements of my code rely on design patterns like the
Singleton
pattern which in turn depend on private constructors. I could
refactor
my code but, ultimately, I would lose the benefits of the
pattern
(ie. one and only one instance of the Singleton class).
I have also used private constructors to simulate enumerated
types
much like the enums you would find in Java 5 and up. But I
can't
use the same implementation in AS3 without private
constructors.
I do not want to resort to mixing legacy code with new AS3
code to
keep functionality intact. Are there any possible
work-arounds for
this issue?
If not, are there any lobbying groups I need to know about so
that
we can get this feature back?http://www.gskinner.com/blog/archives/2006/07/as3_singletons.html
-
Hi everyone,
You can define enum's constructors with private and default access.
Why default ? Is it for programmers' convenience (so they don't have to
type 'private' manually) ?
Cheers,
AdrianNo , your answer is wrong .
The enum's constructror cannot ever be used directly , i.e suppose you have enum class E , you cannot ever write in your code :
E e = new E() (even inside E !!)
Enums private constructor(s) are alsways invoked automaticaly , from within the enum class itself .
So the question is again ... why default access constructors are allowed if no one can ever use them ?
Maybe you are looking for
-
HP LaserJet Pro MFP M127nw ePrint fails occasional​ly
We have setup a "HP LaserJet Pro MFP M127nw" printer to print out orders from the website. The way we setup is 1. Customer completed an order. 2. an email send to the printer's email address. Then the printer will print this out. It works maybe 60%
-
Hi Guru, My client want to create new internal order type. so My doubt is new order type need to create directly in production server or not. Because development server orders type and production server order type there is some miss match is there. K
-
Submit by Email... but to where?
I have created a form for users to fill with a "Submit by Email" button for users to send in their finished form. I created the "Submit by Email" as standard button object, contol type:Submit, submit as:PDF, and submit to URL: [email protected] While
-
Design options for interfacing RFC as Receiver
hello guys , Need some ideas in developing a scenario for interfacing RFC as receiver from a stored procedure call on DB side , what would be best and easy way to interface this RFC? Best regards Krishna
-
Intermitten Errors when running reports in Crystal Report Viewer
Hi All, We get intermittent errors when running the same crystal report over and over again. Most of the time, it would run perfectly fine. Once in a while we would see the error message below displayed... Failed to open the connection. Failed to o