java Reuse existing object - java

I can solve this problem using singleton pattern. But problem is I don't have control on other application which is going to call new MyClass(). Is there any way I can do in implicit constructor of MyClass?. Something like this.
class ClassName {
public ClassName() {
if( object exist for ClassName)
return that
else
create New ClassName object
}
}
Thanks in advance.

You can use a enum:
public enum ClassName {
INSTANCE;
}
Now, you have one instance and you don't have to worry about others instantiating your class.
Is there any way I can do in implicit constructor of MyClass?.
No, that can't be done in a constructor.

If you want to control construction, put in an explicit constructor and declare it private. You can call it from a static factory method, in the class.

This is probably what you want:
public class MySingletonClass {
private static MySingletonClass instance = null;
private MySingletonClass() { }
public static MySingletonClass getInstance() {
if (instance == null) {
instance = new MySingletonClass();
}
return instance;
}
// add your methods here.
}
This way nobody can call new MySingletonClass();. To get the one and only instance of the object you have to write:
MySingletonClass msc = MySingletonClass.getInstance();
or use it somehow like this for void methods:
MySingletonClass.getInstance().yourMethod();
or like this for Methods with a return type:
VariableType foo = MySingletonClass.getInstance().yourMethod(); // Must return VariableType

You would need something like this:
class ClassName {
private static ClassName INSTANCE;
private ClassName() {
//create ClassName object
}
public static ClassName getInstance(){
if (INSTANCE == null){
INSTANCE = new ClassName();
}
return INSTANCE;
}
}
Which is just a basic implementation of the singleton pattern.
If the class that constructs the object HAS to construct it using new, then you are kind of screwed. There is really no way to implement a singleton pattern in Java using only a public constructor.
Edit: You might be able to do something like this:
class ClassNameWrapper extends ClassName {
private final ClassName className;
public ClassNameWrapper(){
className = ClassName.getInstance();
}
//overload methods from ClassName
}
This way, every call to new ClassNameWrapper() will be using the same instance of ClassName.

Create a static variable in your class and hold your object instance there. Expose you class object through a getter method as below:
class ClassName {
private static ClassName myClass= null;
public ClassName getClassName() {
if(myClass == null){
ClassName.myClass = new ClassName();
}
return ClassName.myClass;
}
}

Related

Get an already existing object from another class

Im very new to programming and want to know if I can somehow get the object from a class where I already used new MyClass(); to use it in another class and that I don't need to use new MyClass(); again. Hope you get the point.
Some very simple example:
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass
{
// This is where I want to use the object from class Something()
// like
getObjectFromClass()
}
You can use Singleton pattern to achieve this
This is kickoff example of such object. It has a private constructor and public class method getInstance:
static methods, which have the static modifier in their declarations,
should be invoked with the class name, without the need for creating
an instance of the class
When we make a call to getInstance it checks if an object has been created already and will return an instance of already created objected, if it wasn't created it will create a new object and return it.
public class SingletonObject {
private static int instantiationCounter = 0; //we use this class variable to count how many times this object was instantiated
private static volatile SingletonObject instance;
private SingletonObject() {
instantiationCounter++;
}
public static SingletonObject getInstance() {
if (instance == null ) {
instance = new SingletonObject();
}
return instance;
}
public int getInstantiationCounter(){
return instantiationCounter;
}
}
To check how does this work you can use the following code:
public static void main(String[] args) {
SingletonObject object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
}
Since you have just started coding won't give you a term like reflection and all.. here is one of the simple way is have a public getter() method.
Consider this simple example
class Something {
private int a=10;
public int getA() {
return a;
}
}
Here is the First which has a public method which return the object that i created in this class for the Something Class
class MyFirstClass {
private Something st;
public MyFirstClass() {
this.st = new Something();
}
public Something getSt() {
return st;
}
}
Accessing it from another Class
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt().getA());
}
}
Output: 10
If You wan't to verify
Inject this function in MyFirstClass
public void printHashcode(){
System.out.println(st);
}
and then print the hash codes from both methods in MySecondClass
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt());
my.printHashcode();
}
}
You will see that indeed you are using the Object created in MyFirstClass in MySecondClass.
Because this will give you same hashcode output.
Output On my machine.
Something#2677622b
Something#2677622b
Instead of using the Singleton pattern, a better pattern to use is dependency injection. Essentially, you instantiate the class you want to share, and pass it in the constructor of every class that needs it.
public class MainClass {
public static void main(String[] args) {
SharedClass sharedClass = new SharedClass();
ClassA classA = new ClassA(sharedClass);
ClassB classB = new ClassB(sharedClass);
}
}
public class ClassA {
private SharedClass sharedClass;
public ClassA(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
public class ClassB {
private SharedClass sharedClass;
public ClassB(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
Singleton pattern lets you have single instance which is 'globally' accessible by other classes. This pattern will 'guarantee' that you have only one instance in memory. There are exceptions to one instance benefit, such as when deserializaing from file unless care is taken and readResolve is implemented.
Note that class Something right now has no state(fields), only behavior so it is safe to share between multiple threads. If Something had state, you would need to provide some kind of synchronization mechanism in multi thread environment.
Given such stateless Singleton, it would be better to replace it with class that contains only static methods. That is, unless you are implementing pattern such as Strategy which requires interface implementation, then it would be good idea to cache instance like bellow with Singleton pattern.
You should rework your Something class like this to achieve singleton:
public class Something {
private static final Something INSTANCE = new Something ();
private Something () {
// exists to defeat instantiation
}
public Something getInstance() {
return INSTANCE;
}
public void service() {
//...
}
public void anotherService() {
//..
}
}
If FirstClass and SecondClass are somehow related, you can extract that common object you're using to a super class, and that's the only scope in which you're planning to use this object.
public class SuperClass{
Something st = new Something();
public Something getObjectFromClass(){
return st;
}
}
public class MyFirstClass extends SuperClass{
getObjectFromClass();
}
public class MySecondClass extends SuperClass{
getObjectFromClass();
}
Otherwise, if you plan to use that instance somewhere else you should use a
Singleton object. The easiest way of doing this is:
enum Singleton
{
INSTANCE;
private final Something obj;
Singleton()
{
obj = new Something();
}
public Something getObject()
{
return obj;
}
}
You use it:
Singleton.INSTANCE.getObject();
Okay firstly you can use inheritance e.g.
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass extends myFirstClass
{
// This is where I want to use the object from class Something()
// like
MySecondClass obj = new MySecondClass();
obj.method(); //Method from myfirstclass accessible from second class object
}
Or if you dont want any objects and just the method you can implement interfaces e.g.
public interface MyFirstClass
{
//example method
public abstract void saying(); //no body required
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass implements MyFirstClass //Have to implement methods
{
public void saying(){ //Method implemented from firstClass no obj
System.out.println("Hello World");
}
getObjectFromClass()
}

Refactoring singleton classes that share similar function into a Base class - problems with generics

I am trying to refactor some of my request manager classes that share duplicate code:
public class PayoutChargesManager<T> extends BaseManager<T>{
private static PayoutChargesManager instance = null;
public static synchronized PayoutChargesManager getInstance() {
if (instance == null) {
instance = new PayoutChargesManager();
}
return instance;
}
}
public class PayoutChargesInDayManager<T> extends BaseManager<T> {
private static PayoutChargesInDayManager instance = null;
public static synchronized PayoutChargesInDayManager getInstance() {
if (instance == null) {
instance = new PayoutChargesInDayManager();
}
return instance;
}
}
public class OrdersHistoryManager<T> extends BaseManager<T> {
private static OrdersHistoryManager instance = null;
public static synchronized OrdersHistoryManager getInstance() {
if (instance == null) {
instance = new OrdersHistoryManager();
}
return instance;
}
}
I am trying to only have one copy of getInstance() in my BaseManager, and have PayoutChargesManager, PayoutChargesInDayManager and OrdersHistoryManager reuse it, but I am having some trouble implementing it.
public class BaseManager<T> implements OnApiCallListener {
private static BaseManager<T> instance = null;
public static synchronized BaseManager<T> getInstance() {
if (instance == null) {
instance = new BaseManager()<T>;
}
return instance;
}
}
How do I implement this correctly?
You cannot create an instance of BaseManager<T> using new BaseManager<T>() because T is not an actual type. There needs to be some actual type between the angle brackets. The alternative is to instantiate the raw type BaseManager using new BaseManager(), but that defeats the purpose of your generics and can lead to some awful bugs.
Static methods cannot be overridden by subclasses. They can only be hidden if the subclass declares a static method with the same name.
I would make BaseManager abstract and remove getInstance() from it. You can still have your subclasses inherit common behavior from it, but having a getInstance() method in it is at best confusing and at worst incorrect.
You are probably overcomplicating it. Firstly, the type parameter T will not be available in the context of a static method, so you can never write a common static getInstance() method in your base class.
Besides, you are trying to maintain a single instance of BaseManager (i.e its subtype) - what will happen to other subtypes when of those subtypes occupies the instance reference?
You are better off making the getInstance method abstract (and so non-static) and let the subtypes provide their own implementation (you will lose the singletonness, though). Or write a factory class called Managers that would always get its clients singleton instances of the managers, if you intend to maintain the singletonness.

SingleTon Class creating more than one object when called from outside the class

I wrote a program to call a singleton class from inside the class main. I also wrote an other class from which I am trying to create a object for the Singleton class. I found that I am able to create only one object when I tried from the other class but when I tried to call the method from the same class it creates more than one object. I couldnt understand what is different from same class main method and other class main method.
Here are the classes:
SingleTonClass.java
public class SingleTonClass {
private static SingleTonClass obj = null;
private SingleTonClass() {
System.out.println("Private Constructor is called");
}
public static SingleTonClass CreateObj() {
if (obj == null) {
obj = new SingleTonClass();
}
return obj;
}
public void display() {
System.out.println("The Ojecte creation complete");
}
public void display1() {
System.out.println("The second obj creation is comeplete");
}
public static void main(String[] args) {
SingleTonClass stc = new SingleTonClass();
SingleTonClass stc1 = new SingleTonClass();
SingleTonClass stc2 = new SingleTonClass();
// stc.display();
// stc1.display1();
}
}
SingleTonClassTest.java
public class SingleTonClassTest {
public static void main(String[] args) {
SingleTonClass stc=SingleTonClass.CreateObj();
SingleTonClass stc1=SingleTonClass.CreateObj();
SingleTonClass stc2=SingleTonClass.CreateObj();
}
}
Rather than doing:
private static SingleTonClass obj=null;
You should use: (sorry for changing your weird class name at the same time).
private static final Singleton INSTANCE = new Singleton();
To instantiate the only instance of your Singleton.
After that, you are not going to do some mystical retrieval like:
public static SingleTonClass CreateObj()
{
if (obj==null)
{
obj= new SingleTonClass();
}
return obj;
}
Instead, you should define getInstance() method for retrieving your Singleton.
public static Singleton getInstance() {
return INSTANCE;
}
After these modiciations, your Singleton class should look like the following:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
// This is called only once
System.out.println("Private Constructor is called");
}
public static Singleton getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
// Even if you ask 100 times, this will only return the same INSTANCE
Singleton stc = Singleton.getInstance();
Singleton stc1 = Singleton.getInstance();
Singleton stc2 = Singleton.getInstance();
}
}
And running it will, output:
Private Constructor is called
to your cmd or terminal.
As a final note, as #Swapnil stated already: private Singleton() { ... } declaration is used to indicate that only the Singleton class itself is able to create the instance, which makes sense and rather than doing private static final Singleton INSTANCE = new Singleton(); you can further optimize your code by using an enum constant to store instance (noted by #JonK). For further reading I recommend: singleton pattern in java
Cheers.
The whole point of having a private constructor in implementing a singleton pattern is that you shouldn't be able to invoke it from outside the class, to avoid object creation directly. You're invoking it from inside the class. Hence, the problem.
Singleton is no magic, you need to have a method like getInstance() inside your singleton and this method should ensure there's only once instance.
Rather than creating new object of Singleton class every time get the instance of singleton class. There are various ways to define singleton class.
Here is one way to crate thread safe Singleton class. for more check out this link http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples#bill-pugh-singleton
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
Singleton Class: We can create only one object of this class.
Let's take an example:Since every thing in Java is object so I am giving you a real life example. You have a house and there is lock in it. This lock has only one key and if any one from outside wants to enter or access any thing in your house then he should have that unique key. Means this constraint applies only on outsiders. If anyone already present in the house then he can do anything and there is no restriction for him.
In the same way private constructor does not let any anyone to create second object of that class but you can make multiple objects within the same class because private methods only accessed by same class.
Singleton is Design pattern and here in your code design is like this, CreateObj() is static method of SingletonClass which checks if object is null then create the object by calling the constructor otherwise it is returning the same object.
You can not make objects of singleton class outside the class because the constructor is private.
Constructor instantiate the object. if the constructor itself is private then the object will never be instantiated outside the class rather you can use getInstance method. then you can access its features outside the class.

Java send instanceof as paramater

This might be a stupid question but I gotta know if there is a way to send the instance of a object to a method?
Like this:
public class TestClass
{
public TestClass()
{
//Initialize
}
}
public class AnotherClass
{
Instance!? mInstance;
public AnotherClass(Instance!? instance)
{
mInstance = instance;
}
public boolean isInstanceOfTestClass()
{
return mInstance == TestClass;
}
}
public class Main
{
public static void main(String[] args)
{
AnotherClass a = new AnotherClass(TestClass);
if(a.isInstanceOfTestClass)
System.out.println("lala");
}
}
(Tried to make it wrapped as codeblock)
There's no such thing as an "instance of an object". An object is an instance of a class - so "instance" and "object" refer to the same thing.
You can use the instanceof operator to test if an arbitrary object is an instance of a particular class:
if (a instanceof AnotherClass) {
// ...
}
There's also the class java.lang.Class, which represents the class of an object. You can get it by calling getClass() on an object:
Class<?> cls = a.getClass();
See the API documentation of java.lang.Class.
Well you can use Class.isAssignableFrom and construct with an instance of Class where T is the class you want to test for.
But if you are bothered about about enforcing typing and making non-type specific classes I suggest you read up on generics.

Accessing constructor of an anonymous class

Lets say I have a concrete class Class1 and I am creating an anonymous class out of it.
Object a = new Class1(){
void someNewMethod(){
}
};
Now is there any way I could overload the constructor of this anonymous class. Like shown below
Object a = new Class1(){
void someNewMethod(){
}
public XXXXXXXX(int a){
super();
System.out.println(a);
}
};
With something at xxxxxxxx to name the constructor?
From the Java Language Specification, section 15.9.5.1:
An anonymous class cannot have an
explicitly declared constructor.
Sorry :(
EDIT: As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example:
public class Test {
public static void main(String[] args) throws Exception {
final int fakeConstructorArg = 10;
Object a = new Object() {
{
System.out.println("arg = " + fakeConstructorArg);
}
};
}
}
It's grotty, but it might just help you. Alternatively, use a proper nested class :)
That is not possible, but you can add an anonymous initializer like this:
final int anInt = ...;
Object a = new Class1()
{
{
System.out.println(anInt);
}
void someNewMethod() {
}
};
Don't forget final on declarations of local variables or parameters used by the anonymous class, as i did it for anInt.
Here's another way around the problem:
public class Test{
public static final void main(String...args){
new Thread(){
private String message = null;
Thread initialise(String message){
this.message = message;
return this;
}
public void run(){
System.out.println(message);
}
}.initialise(args[0]).start();
}
}
I know the thread is too old to post an answer. But still i think it is worth it.
Though you can't have an explicit constructor, if your intention is to call a, possibly protected, constructor of the super class, then the following is all you have to do.
StoredProcedure sp = new StoredProcedure(datasource, spName) {
{// init code if there are any}
};
This is an example of creating a StoredProcedure object in Spring by passing a DataSource and a String object.
So the Bottom line is, if you want to create an anonymous class and want to call the super class constructor then create the anonymous class with a signature matching the super class constructor.
Yes , It is right that you can not define construct in an Anonymous class but it doesn't mean that anonymous class don't have constructor. Confuse...
Actually you can not define construct in an Anonymous class but compiler generates an constructor for it with the same signature as its parent constructor called. If the parent has more than one constructor, the anonymous will have one and only one constructor
You can have a constructor in the abstract class that accepts the init parameters. The Java spec only specifies that the anonymous class, which is the offspring of the (optionally) abstract class or implementation of an interface, can not have a constructor by her own right.
The following is absolutely legal and possible:
static abstract class Q{
int z;
Q(int z){ this.z=z;}
void h(){
Q me = new Q(1) {
};
}
}
If you have the possibility to write the abstract class yourself, put such a constructor there and use fluent API where there is no better solution. You can this way override the constructor of your original class creating an named sibling class with a constructor with parameters and use that to instantiate your anonymous class.
If you dont need to pass arguments, then initializer code is enough, but if you need to pass arguments from a contrcutor there is a way to solve most of the cases:
Boolean var= new anonymousClass(){
private String myVar; //String for example
#Overriden public Boolean method(int i){
//use myVar and i
}
public String setVar(String var){myVar=var; return this;} //Returns self instane
}.setVar("Hello").method(3);
Peter Norvig's The Java IAQ: Infrequently Answered Questions
http://norvig.com/java-iaq.html#constructors - Anonymous class contructors
http://norvig.com/java-iaq.html#init - Construtors and initialization
Summing, you can construct something like this..
public class ResultsBuilder {
Set<Result> errors;
Set<Result> warnings;
...
public Results<E> build() {
return new Results<E>() {
private Result[] errorsView;
private Result[] warningsView;
{
errorsView = ResultsBuilder.this.getErrors();
warningsView = ResultsBuilder.this.getWarnings();
}
public Result[] getErrors() {
return errorsView;
}
public Result[] getWarnings() {
return warningsView;
}
};
}
public Result[] getErrors() {
return !isEmpty(this.errors) ? errors.toArray(new Result[0]) : null;
}
public Result[] getWarnings() {
return !isEmpty(this.warnings) ? warnings.toArray(new Result[0]) : null;
}
}
It doesn't make any sense to have a named overloaded constructor in an anonymous class, as there would be no way to call it, anyway.
Depending on what you are actually trying to do, just accessing a final local variable declared outside the class, or using an instance initializer as shown by Arne, might be the best solution.
In my case, a local class (with custom constructor) worked as an anonymous class:
Object a = getClass1(x);
public Class1 getClass1(int x) {
class Class2 implements Class1 {
void someNewMethod(){
}
public Class2(int a){
super();
System.out.println(a);
}
}
Class1 c = new Class2(x);
return c;
}

Categories

Resources