[英]Getting an object of a private class in java
I am not so proficient in java, and have a small question. 我不太精通Java,有一个小问题。
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? 我的问题是,如果getB()仅返回新的B()而不是新的B.get(),有什么区别?当您返回B()。get()时,它是否只是一种好的软件工程,还是有一些更深层次的推理方法? ?
The return this
returns current instance of B
. return this
返回值返回B
当前实例。 In your case new B().get();
在您的情况下, new B().get();
returns new instance of B
(created right now). 返回B
新实例(立即创建)。
So return new B().get();
因此return new B().get();
and new B()
do the same and equivalent. 和new B()
相同且等效。
The get()
method or I would say getInstance()
method we can use in Singleton pattern, like: 我们可以在Singleton模式中使用的get()
方法或我想说的getInstance()
方法,例如:
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 因此,无论我们调用getInstance()
多少次,它都会返回相同的实例
基本上返回“ 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). 因为当您创建一个new B()
JVM将为该对象分配一个新的地址(例如:100001F),并且当您调用new B().get()
,它将返回相同的地址(100001F)。 If you just return new B()
, it will return the same address (100001F). 如果仅返回new B()
,它将返回相同的地址(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. 我的特别意见: return new B()
是最好的选择,因为它分配对象并返回地址,而不是分配和稍后调用get()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.