0xhacker
0xhacker

Reputation: 1119

Getting an object of a private class in java

I am not so proficient in java, and have a small question.

A lot of times I see the following code:

public class A
{
   private class B {

       B() {
       }

       get() {
       return this;
       }
   }

   public B getB() {
      return new B().get();
   }    
}

My question is, what is the difference if getB() just returns new B() instead of new B.get() Is it just good software engineering when you do return B().get(), or is there some deeper reasoning?

Upvotes: 1

Views: 110

Answers (3)

Cold
Cold

Reputation: 797

There's no difference. Because when you create a new B() JVM will allocate a new addres for the object (eg: 100001F), and when you call new B().get() it will return the same address (100001F). If you just return new B(), it will return the same address (100001F).

My particular opinion: return new B() is the best option, because it allocate the object and return the address, instead of allocate and later invoque get() method.

Upvotes: 0

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

The return this returns current instance of B. In your case new B().get(); returns new instance of B (created right now).

So return new B().get(); and new B() do the same and equivalent.

The get() method or I would say getInstance() method we can use in Singleton pattern, like:

public class B {

 private static B instance = null; 

  public static B getInstance(){
   if(instance == null){
       instance = new B();
    }

    return instance;
  }    
} 

So no matter how many times we call getInstance(), it returns the same instance

Upvotes: 1

Marin
Marin

Reputation: 189

basically methods that return "this" are useless - the code that is supposed to call this method already has reference to the object

Upvotes: 0

Related Questions