简体   繁体   中英

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?

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

基本上返回“ this”的方法是没有用的-应该调用该方法的代码已经引用了该对象

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM