我对java不太精通,有一个小问题。
很多时候我看到下面的代码:
public class A
{
private class B {
B() {
}
get() {
return this;
}
}
public B getB() {
return new B().get();
}
}
我的问题是,如果 getB() 只返回 new B() 而不是 new B.get() 有什么区别 当你返回 B().get() 时,这只是良好的软件工程,还是有一些更深层次的推理?
最佳答案
return this
返回B
的当前实例。在您的情况下,new B().get();
返回B
的新实例(立即创建)。
因此,return new B().get();
和 new B()
执行相同且等效的操作。
我们可以在单例模式中使用 get()
方法,或者我会说 getInstance()
方法,例如:
public class B {
private static B instance = null;
public static B getInstance(){
if(instance == null){
instance = new B();
}
return instance;
}
}
因此,无论我们调用 getInstance()
多少次,它都会返回相同的实例
关于java - java中获取私有(private)类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19282037/