I've got a singleton class, which functions perfectly fine. I now just wonder what the last method is for?
public class PicassoSingleton {
private static Picasso instance;
public static Picasso with(Context context) {
if (instance == null) {
instance = new Picasso.Builder(context.getApplicationContext()).debugging(true).downloader(new ImageDownloader(context)).build();
}
return instance;
}
private PicassoSingleton() {
throw new AssertionError("No instances.");
}
}
Does anybody know what it does or what the use is?
Normally it would be enough to make the constructor private to prevent others classes from instantiating a PicassoSingleton.
Throwing an exception in the private constructor seems to be paranoid programming, because the implementor of a class knows it's internal details and must know what he does.
But there is one reason when it makes sense. Throwing an exception in the constructor will also prevent others from using reflection to instantiate an object of the class.
This will be impossible
Constructor<PicassoSingleton> constructor = PicassoSingleton.class.getDeclaredConstructor();
constructor.setAccessible(true);
constructor.newInstance(); // will throw the AssertionError - impossible to instantiate it
It prevents the class from being instantiated, if you have no constructor specified then all classes by default can have a new instance created using new PicassoSingleton() with no arguments.
If you specify a constructor and make it private then only the class itself can create instances of itself. If you then throw an exception inside the constructor not even the class can instantiate itself and it prevents people using reflection from doing so.
Doing this essentially means that the class can provide static methods, variables, etc but can never be used as an object (unless you provide another constructor, in which case the access levels of that constructor may allow it to be used).
That's the constructor for the PicassoSingleton class. It's private to make sure you can't call it from other code. Instead, you use the with method to obtain the singleton instance of the class.
private PicassoSingleton() {
throw new AssertionError("No instances.");
}
Constructor is made private so that no new instances of the class can be created using new keyword.
PicassoSingleton is a constructor here and by making it private you are restricting other class to instantiate this.
This make the constructor unavailable to other classes and an instance of this class can only be accessed via getInstance method.
In additional to Tim B answer I want to say that, not only that you prevent this class from been used as object, you also prevent other classes to extend it.
How ever you do not have to throw exception in the constructor you can just leave it blank, the only reason to do it is protection from your self.
public static Picasso with(Context context) {
if (instance == null) {
instance = new Picasso.Builder(context.getApplicationContext()).debugging(true).downloader(new ImageDownloader(context)).build();
}
return instance;
}
this method is use to access private field "instance" and it is static bcoz then you can directly access it with its class name without making objects. and it is a public method because you may need to access it from outside of the current package. initially it is check whether instance variable is null or not. if null, then it is not already initiated. then it will create a new Object and initiate it. and finally return the instance object reference. this kind of methods are called accessior methods in programming.
private PicassoSingleton() {
throw new AssertionError("No instances.");
}
this is the constructor of the PicassoSingleton class. according to theory of Singleton design pattern definition, it should not allow to make objects of the class. to do it we can make a private constructor. private modifier is access only within the same class. So at the developing time someone mistakenly create a instance to this class it will throw a Assertion Error by telling "No Instances"
hope you get what i mean.
finally one word about class field
private static Picasso instance;
this object reference variable is to hold the object reference. and it is private to limit the access from outside of the class. and it is static reference bocz it is access from static method.
Related
public class DBSingleton {
private static DBSingleton instance = new DBSingleton();
private DBSingleton() {
// why do we need this constructor
}
public static DBSingleton getInstance() {
return instance;
}
}
How private constructor can help me?
I mean all variables and methods are static and even if I leave constructor public it will not change anything.
lets say someone create an object of my singleton nothing will happen because everything inside this class is static which means associated with the class itself not with object. Java static property is shared to all objects.
can anyone give me reasonable example please
You need a private constructor to prevent user from instantiating your class.
If you make your constructor public, users could do DBSingleton singleton = new DBSingleton() and your class will not be a Singleton!
A singleton class (edit: compare with singleton instance - see comments) doesn't even necessarily need to be instantiated; it's enough to give it a private constructor and declare all other methods static, forcing the user to invoke them on the class.
The constructor has to be private in order to ensure the class is a singleton, whether or not you create a single instance of it. If no private constructor were declared, Java would automatically provide a public no-arg constructor for it.
The class needs to be a single instance presumably for safety, namely, in cases where you want to invoke methods on it that do exactly what that singleton says they do. If you have an instance of a class that isn't explicitly made a singleton, then there's no guarantee when you invoke methods on it that it's running the singleton's implementation, because you might in fact have a subclass of DBSingleton in which said method is overridden. (If you invoke them as DBSingleton.someMethod(), you will of course get the expected behavior, but if you're doing this:
DBSingleton dbsInstance = DBSingleton.getInstance();
// ... all sorts of code, some of which might affect dbsInstance
dbsInstance.someMethod();
all bets are off.)
The more proper way to declare a class to avoid other instances of it is to declare it final. You give it a private constructor so that it also cannot be instantiated. (Either a final class or a class with a private constructor (or rather, zero non-private constructors) suffices to make the class non-overrideable.)
Could the uniqueeInstance have one and only one instance?
public class A {
private static A uniqueInstance = new A();
private A() {}
public static A getInstance() {
return uniqueInstance;
}
}
This is a Singleton pattern, it's purpose is to have only one possible instance for a class.
This is why you have a private constructor , so that no other class can attempt to instantiate it directly.
Here are more elaborate thoughts for possible uses of a Singleton :
When to use the Singleton
It is not guaranteed.
By reflection you are easy to get more instances.
The only way to guarantee that you have exactly one instance is to use an enum:
enum Holder {
INSTANCE;
//Keep in Mind of A you may still have more instances. if you want to have the
//guarantee to have only one instance you may need merge the whole class
//into an enum (which may not be possible)
public A uniqueInstance = new A();
}
Other ways like throwing an exception in the constructor are generally also possible. But not completely secure since there are ways to create an Object without calling any constructor.
final class AbsTest {}
class BTest extends AbsTest {}
How to prevent creation of subclass(es) without using the final keyword?
Here are the few options
Create Private Constructor
make each method final, so people can't override them. You avoid accidental calling of methods from subclass this way. This doesn't stop subclassing though.
put check into constructor for class:
if (this.getClass() != abc.class)
{
throw new RuntimeException("Subclasses not allowed");
}
But final is provided to solve such problem I must say, so better to go with final!!!
In above code how to prevent to create subclass without use of "final"
keyword
You can declare private constructors to avoid creation of Object.
private AbsTest() {
}
Using Java reflection, one can instantiate an object of a class, even via a private constructor, e.g. for
public class MyClass
{
private MyClass(Object p1, String p2)
{
// Constructor with no modifications to static code
}
}
one can do (in the same or any other class, exception handling omitted for simplification)
public static final Constructor myClass;
static
{
myClass = MyClass.class.getConstructor(Object.class, String.class);
myClass.setAccessible(true);
}
and then create new instances of MyClass like
myClass.newInstance(new Object(), "Test");
Is the above call to newInstance() thread-safe, given that myClass is static?
Calling Constructor.newInstance() does not seem to be strictly thread-safe; at least in my openjdk-6 implementation I find a class sun.reflect.NativeConstructorAccessorImpl having a field defined as private int numInvocations; and later on this line of code: if (++numInvocations > ReflectionFactory.inflationThreshold()) { - which may certainly behave otherwise as expected.
Also, in the Constructor class itself, the method acquireConstructorAccessor() is documented with "NOTE that there is no synchronization used here".
But the dodgy behaviour does not seem to result in an overall unexpected behavior, only doing things repeatedly/unnecessarily, thus calling newInstance() in parallel would NOT result in something being screwed up.
Obviously, you can still mess things up with what's done within the instance constructor.
Yes, the class instance is static, and the constructor is thread safe, as long as it is not doing anything non-thread safe with the static context of the object.
Is there any other method of stopping inheritance of a class apart from declaring it as final or by declaring its constructor as private?
A comment
//Do not inherit please
Two more options:
make each method final, so people can't override them. You avoid accidental calling of methods from subclass this way. This doesn't stop subclassing though.
put check into constructor for class:
if (this.getClass() != MyClass.class) {
throw new RuntimeException("Subclasses not allowed");
}
Then nobody will be able to instantiate subclass of your class.
(Not that I suggest using these techniques, it just came to my mind. I would use final class and/or private constructor)
Use final
Use private constructors
Use a comment:
// do not inherit
Use a javadoc comment
Make every method final, so people can't override them
Use a runtime check in the class constructor:
if (this.getClass() != MyClass.class) {
throw new RuntimeException("Subclasses not allowed");
}
Final was created to solve this problem.
Make your constructors private and provide factory functions to create instances.
This can be especially helpful when you want to choose an appropriate implementation from multiple, but don't want to allow arbitrary subclassing as in
abstract class Matrix {
public static Matrix fromDoubleArray(double[][] elemens) {
if (isSparse(elements)) {
return new SparseMatrix(elements);
} else {
return new DenseMatrix(elements);
}
}
private Matrix() { ... } // Even though it's private, inner sub-classes can still use it
private static class SparseMatrix extends Matrix { ... }
}
Using final is the canonical way.
public final class FinalClass {
// Class definition
}
If you want to prevent individual methods from being overridden, you can declare them as final instead. (I'm just guessing here, as to why you would want to avoid making the whole class final.)
I'd have to say it's typically bad form. Though there are almost always cases where something is valid, I'd have to saying stopping inheritance in an OO world is normally not a good idea. Read up on the Open-Closed Principle and here. Protect your functionality but don't make it impossible for the guy who comes in and supports it...
Without using a final class, you can basically make all the constructors private:
public class A {
private A() {} //Overriding default constructor of Java
}
Which although will also make this class abstract-ish by disallowing creating an object of this class, yet as any inheritance requires super(); in the constructor, and because the constructor is private, a compilation error will be the maximum you can get when one tries to inherit that class.
Yet, I would recommend using final instead as it is less code and includes the option of creating objects.