[英]When to use an object to call a method?
I am confused on when to use an object to call a method.我对何时使用 object 调用方法感到困惑。 For instance, sometimes I have to do object.someMethod()
and other times the method works when it is just called someMethod()
.例如,有时我必须执行object.someMethod()
,而其他时候该方法仅在称为someMethod()
时才有效。 If anyone could clarify when I need to use an object and when I do not, that would be great!如果有人能澄清我什么时候需要使用 object 而我不需要,那就太好了!
When you are calling non-static class members, you always need to specify the instance.当您调用非静态 class 成员时,您始终需要指定实例。 However, there is one short-cut if you are inside a member function: Instead of writing this.otherMethod()
, you can omit the this.
但是,如果您在成员 function 中,则有一个捷径:您可以省略 this.otherMethod() 而不是编写this.otherMethod()
this.
part and only write otherMethod()
, as it will be implicitly assumed by the compiler.部分并且只写otherMethod()
,因为它会被编译器隐式假定。 It is a common situation and readability is not hurt from omitting it:这是一种常见的情况,省略它不会损害可读性:
class Foo {
public void someMethod() {
otherMethod(); // same as calling: this.otherMethod()
}
public void otherMethod() {
}
}
MyClass object = new MyClass();
object.someMethod();
MyClass object2 = new MyClass();
someMethod(); // ERROR: from the context, it is not clear which instance is meant:
// Do you mean object.someMethod() or object2.someMethod()?
Note that it only works for methods of the same class.请注意,它仅适用于相同 class 的方法。 If you call it from outside, it will be a compile error.如果你从外部调用它,这将是一个编译错误。 In the example above, it is mandatory that you explicitly write object.someMethod()
or object2.someMethod()
.在上面的示例中,您必须明确编写object.someMethod()
或object2.someMethod()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.