Difference between calling new and getInstance() - java

Is calling Class.getInstance() equivalent to new Class()?
I know the constructor is called for the latter, but what about getInstance()?
Thanks.

There is no such method as Class#getInstance(). You're probably confusing it with Class#newInstance(). And yes, this does exactly the same as new on the default constructor. Here's an extract of its Javadoc:
Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.
In code,
Object instance = Object.class.newInstance();
is the same as
Object instance = new Object();
The Class#newInstance() call actually follows the Factory Method pattern.
Update: seeing the other answers, I realize that there's some ambiguity in your question. Well, places where a method actually named getInstance() is been used often denotes an Abstract Factory pattern. It will "under the hoods" use new or Class#newInstance() to create and return the instance of interest. It's just to hide all the details about the concrete implementations which you may not need to know about.
Further you also see this methodname often in some (mostly homegrown) implementations of the Singleton pattern.
See also:
Real world examples of GoF design patterns.

Absolutely (usually) not.
getInstance is the static method often used with the Singleton Pattern in Java. The new keyword actually creates a new object. At some point there must be a new (although there are a few other methods to instantiate new objects) to actually create the object that getInstance returns.

In the context of an abstract class, a getInstance() method may represent the factory method pattern. An example is the abstract Calendar class, which includes static factory methods and a concrete subclass.

Some abstract classes have getInstance() methods because you can't instantiate an abstract class by using new keyword.

Yes, this is often used in Singleton Pattern. It`s used when You need only ONE instance of a class.
Using getInstance() is preferable, because implementations of this method may check is there active instance of class and return it instead of creating new one. It may save some memory. Like in this example:
public static DaoMappingManager getInstance() {
DaoProperties daoProperties = null;
try {
daoProperties = (DaoProperties) DaoProperties.getInstance();
} catch (PropertyException e) {
e.printStackTrace();
}
return getInstance(daoProperties);
}
public static DaoMappingManager getInstance(DaoProperties daoProperties) {
if (instance == null) {
instance = new DaoMappingManager(daoProperties);
}
return instance;
}

For start:
newInstance() is a static method. This means you can access to it without creating new class directly! And it creates that class itself "with necessary inits" (via an inner new myClass()). This means you can add some newInstance methods (newInstance4usage1, newInstance4usage2,...) for different needs that per static method creates class with different initialization.
Sometimes, this helps class's user (final programmer) to creating class without any worry and very comfortable.
This helps really when the init process is complex or has important or or usual levels. this method don't prevent from creating class by new keyword.
I like it!
Excuse me for slow answering, I am typing with my mobile phone!

Related

Same instance sharing with multiple requests in Java (OOP)

I have one class whose single instance needs to be used by multiple classes in Java. I found two solutions for the same:
1. Pass the instance as method parameters
2. Use Static factory
My question is if I used static factory, how can I differentiate the incoming requests when I am using the static method. I want to avoid the 1st solution as there are many classes that are going to use this instance. Also, recommend the best design if other than mentioned above.
Code Example:
class MyClass{
Map<String, List<String>> myMap=new ConcurrentHashMap();
public static void addToMap(String key, String value){
if(myMap.containsKey(key)){
List<String> stringList=myMap.get(key);
stringList.add(value);
}
else{
myMap.put(key,value);
}
}
}
I want to perform this add method at many places while program execution for eg:
Method addEmployee():
if(employeeName==null){
MyClass.addToMap("ER101", "Name Error");
}
Method insertInDB():
catch(SQLException e){
MyClass.addToMap("SQL", "Error Occurred in DB Operation");
}
Thanks
There are a number of ways to make the same instance of a class available to different callers such as threads or requests.
One of the easiest things you can do is create a singleton as shown above. The problem with singletons is that there can only ever be one of them, as they are generally set up to enforce that there is a single instance of them.
Better is to create your instance, and pass it to the things that need it. If you're creating a web application or similar, you can use a Dependency Injection framework such as SpringFramework to achieve this.
Injecting your instance where it is needed will mean it will be easier to replace this instance with a dummy instance for testing, and during testing you'll be able to create many instances of this class configured in different ways to test.
As 12dollar says: Use the Singleton Design Pattern, and ask for that instance to the Singleton Class:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Then you could call getInstance().
The best design would be to make your class as Singleton class.
For your usage i think you can follow the below steps,
make your constructor as private.
then, have a static function inside that class to return the instantiated object of your class.
you can have your own if(classobj==nul) check to verify if its already instantiated or not(only on first call it will be null , further calls it wont be null) and return the object.
Cheers :)

Can objects have access modifiers?

I was going through a piece of code when I came across this:
public class ClassicA {
private static ClassicA instance = null;
}
I have never used such a thing and wanted to know what it means and how it is used. Also, what is the purpose of the access modifier for the object? Any examples/links are welcome.
It probably means that ClassicA is a Singleton. It is usually involved with declaring a private constructor, and a single public static getInstance() method.
Singletons are used when you want to make sure there is only one global instance of ClassicA in your entire application. Instead of instantiating it, you call getInstance(), which will check if it was instantiated once or not. If it was, it will instantiate it, and store the the resulting object in the private instance field. If it was already constructed, just return the instance field without re-instantiating.
Note that this is considered bad practice. See: https://softwareengineering.stackexchange.com/questions/40373/so-singletons-are-bad-then-what
Well, the class ClassicA has a private and static field instance which is null.
If there are no getters/setters the only way to access that field would be using reflection.
Since this looks like a singleton, I guess there's a getter as well that returns instance and if it is null first creates an instance and assigns it to the field.
It's a (static) member of the class, and yes, these can have access modifiers. (And as others have noted, it indeed looks like a portion of a Singleton.)
its a singleton
basically the author intended there to be only 1 instance of this class alive (the instance field)
the constructor is probably private and used only within the class.
This is used typically for a class that exhibits the Singleton design pattern.
The point is that for these types of objects you only want a single instance at most. What you do is create a private constructor for the class and then usually a public static method called, getInstance in which you check if the private instance variable has been set yet or not. If it has not yet set, you create a new instance of the class and assign it to instance, then you return that instance. If the object was already created you simply return it. Like this:
public class MySingleton {
private static MySingleton instance=null;
private MySingleton() {
//do stuff
}
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
}
Then from throughout your program you can easily get the singleton object from anywhere.
Thus, a singleton is effectively just a glorified global variable in languages such as PHP. I would argue though that it is a lot cleaner as you can prevent others from reassigning the reference to the instance and other trickery that may be very bad from a design standpoint.
Typically people use it for classes that manage some type of data access, such as a DB object, for Factory classes and builder classes, see this for more info
This is used for singleton pattern. See here
private static means that the instance is available to all the instances and static methods of the class, but only to them. It's actually like having static private method.
Such tricks can be used for example for implementing a singleton: you keep internally a single instance of a class, and you can give it to the class's clients on demand. Or for any other case when you need something shared just between the static methods and instances of some class.

How many instances of the Factoryclass will be created

public class Factoryclass
{
public static MyClass returnObject(String str)
{
// Based on the parameter passed it will retrn some class
}
}
If in a Web Application , theer were 100 requests .
Now please tell me how many objects of Factoryclass will be created ??
if you do
Factoryclass.returnObject()
no Factoryclass instances will be created, unless you do new Factoryclass() inside the returnObject method
It entirely depends on the content of your method returnObject(). The fact that it's a static method only means that it is "stateless" and doesn't pull from non-static instance members in order to work. However, you could potentially instantiate a new instance with each and every time it has been called.
The fact that it's a factory leads me to think that is, in fact, the case. However, the nature of the factory pattern would suggest that it should not matter to you whatsoever. If your implementation depends on the fact that this Factoryclass returns multiple instances or the same instance, someone made a wrong decision in making it a factory.

How to check if there is any instance of a class at runtime?

Is there any method to check whether any instance of a class is running?
I have a GUI and I don't want open another instance of it, if a one is already running.
I know about including a counter in constructor. Any method except that?
Thanks in advance!!
Use the singleton pattern.
Here is a simple implementation in java of a singleton:
public class MyClass {
private static MyClass INSTANCE = new MyClass();
private MyClass() { // private constructor prevents creation outside class
}
public static MyClass getInstance() {
return INSTANCE;
}
}
Note that this is not "bulletproof" (there are "hacks" you can use via reflection to circumvent this and create two instances), however if you're the only user of the code it will be fine.
Is there any method to check whether any instance of a class is running?
The simple answer is No.
The normal way to deal with this problem is to use the Singleton design pattern. The idea of the pattern is that you write the code to remove the possibility of creating multiple instance of the class.
In Java you typically do this by declaring the class constructor to be private, and providing access to the singleton instance via a static method. Depending on your precise requirements, the singleton can be created eagerly or lazily.
Bohemian's answer provides a good example of this approach.
(In Java 5 or later, it is also possible to use enum types to implement singletons.)
Use Enum as recommended by J. Bloch (Effective Java Programming 2nd Ed., Addison Wesley)

How do I find where an instance of a Java singleton is created?

In a large, complex program it may not be simple to discover where in the
code a Singleton has been instantiated. What is the best approach to keep track of created singleton instances in order to re-use them?
Regards,
RR
A Singleton usually has a private constructor, thus the Singleton class is the only class which can instantiate the one and only singleton instance.
It's the responsibilty of singleton class developer to make sure that the instance is being reused on multiple calls.
As a user, you shouldn't worry about it.
class Singelton
{
private static Singelton _singelton = null;
private Singelton()
{
}
// NOT usable for Multithreaded program
public static Singelton CreateMe()
{
if(_singelton == null)
_singelton = new Singelton();
return _singelton;
}
}
Now, from anywhere in your code, you can instantiate Singelton, how many times you like and each time assign it to different reference. but c'tor is called ONLY once.
I would use an enum
enum Singleton {
INSTANCE:
}
or something similar which cannot be instantiated more than once and globally accessible.
General practice for naming methods which create/return singletons is getInstance(). I don't understand the situation when you can't find the place in code where singletons created, but you can search for this method name.
If you want to catch the exact moment of singleton creation - you can use AOP. AspectJ is a good example in java. You will be able to execute your code before/after creation of class or calling getInstance() method.
If your question is about reusing of created Singletons, then search this site. For example

Categories