在引用变量上调用方法vs在新对象上调用方法 [英] Calling methods on reference variable vs Calling methods on a new object
问题描述
我在调用非静态方法时感到困惑
I'm having confusion in calling a non-static method
class A {
void doThis() {}
public static void main(String... arg) {
A a1 = new A();
a1.doThis(); // method - 1
new A().doThis(); // method - 2
}
}
我知道两者都 method-1 和 method-2 会调用 doThis(),但有任何功能差异吗? 方法-2 中新对象的引用是什么。
I know that both method-1 and method-2 will call doThis(), but is there any functional difference? What will be the reference of new object in method-2.
推荐答案
是否有任何功能差异?
Is there any functional difference?
两者的行为方式相同。
第二个选项不允许您再次重用该实例。在单行返回语句中它可能是方便和简洁的(例如,考虑每个构造方法返回半初始化实例的构建器模式):
The second option doesn't allow you to reuse that instance again. It may be convenient and concise in one-line return statements (for instance, consider the builder pattern where each constructing method returns a half-initialised instance):
return new Builder().a().b().build();
或创建对象时仅执行一次定义的操作。
or if an object was created only to perform a defined action once.
方法-2中新对象的引用是什么?
What will be the reference of a new object in method-2?
它不再存在(更准确地说,我们无法访问它),除非 doThis
返回这个
你可以在方法执行后放入一个变量。
It is no longer exist (more precisely, we don't have access to it) unless the doThis
returns this
which you could be able to put in a variable after method execution.
我可以说这个方法 - 2是一种调用非静态方法的不正确方法吗?
Can I say that method-2 is an improper way of calling a non-static method?
否。如果之后永远不会使用这个变量,我们为什么要创建一个变量?
No. Why should we create a variable if this variable will never be used afterwards?
这篇关于在引用变量上调用方法vs在新对象上调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!