1
public class Appointment{
    public TimeInterval getTime();
    {/*implementation not shown*/}

    public boolean conflictsWith(Appointment other)
    {
     return getTime().overlapsWith(other.getTime());
    }
}

public class TimeInterval{
    public boolean overlapsWith(TimeInterval interval)
    {/*implementation not shown*/}
}

我的问题在于return getTime().overlapsWith(other.getTime())陈述。getTime()不是静态方法,所以我认为它只能在引用对象时使用。但是从该声明中,没有提到任何对象。我知道它会getTime()为后续方法返回一个对象,但它本身呢?我的同学解释说“当我们要使用该conflictsWith()方法时,我们会声明一个对象,因此return语句将相当于return object.getTime().overlapsWith(other.getTime());”这种解释是否正确?那么这是否意味着当我们在方法中使用非静态方法时,不需要引用对象?

4

3 回答 3

6

由于getTime()不是静态方法,因此在当前对象上调用它。实现相当于

public boolean conflictsWith(Appointment other)
{
  return this.getTime().overlapsWith(other.getTime());
}

您只会调用conflictsWith()一个Appointment对象,如下所示:

Appointment myAppt = new Appointment();
Appointment otherAppt = new Appointment();
// Set the date of each appt here, then check for conflicts
if (myAppt.conflictsWith(otherAppt)) {
  // Conflict
}
于 2012-04-05T02:13:52.700 回答
2

调用非静态方法时,对象this是隐含的。在运行时,this对象指的是正在操作的对象的实例。在您的情况下,它指的是调用外部方法的对象。

于 2012-04-05T02:12:53.150 回答
0

在 Appointment 内部,getTime() 等价于 this.getTime()。

您的 conflictWith 可以这样重写:

TimeInterval thisInterval = this.getTime(); // equivalent to just getTime()
TimeInterval otherInterval = object.getTime();
return thisInterval.overlapsWith(otherInterval);
于 2012-04-05T02:20:18.203 回答