【问题标题】:When to use an object to call a method?何时使用对象调用方法?
【发布时间】:2020-05-08 22:06:50
【问题描述】:

我对何时使用对象调用方法感到困惑。例如,有时我必须执行object.someMethod(),而其他时候该方法仅在称为someMethod() 时才有效。如果有人能澄清我什么时候需要使用一个对象,什么时候不需要,那就太好了!

【问题讨论】:

  • someMethod() 仅在方法与您调用someMethod() 的方法属于同一类 时才有效。或者如果方法是static-imported。

标签: java oop object methods


【解决方案1】:

当你调用非静态类成员时,你总是需要指定实例。但是,如果您在成员函数内部,则有一个捷径:您可以省略this. 部分而只写otherMethod(),而不是编写this.otherMethod(),因为编译器会隐式假定它。这是一种常见的情况,省略它不会损害可读性:

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()?

请注意,它仅适用于同一类的方法。如果你从外部调用它,这将是一个编译错误。在上面的示例中,您必须显式写入object.someMethod()object2.someMethod()

【讨论】:

    猜你喜欢
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多