使用非静态方法而不将其引用到对象?

时间:2012-04-05 02:10:56

标签: java object methods

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());”这个解释是否正确?那么这意味着当我们在方法中使用非静态方法时,不需要引用任何对象吗?

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:2)

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

答案 2 :(得分:0)

Inside Appointment中,getTime()等同于this.getTime()。

你的冲突可以这样改写:

TimeInterval thisInterval = this.getTime(); // equivalent to just getTime()
TimeInterval otherInterval = object.getTime();
return thisInterval.overlapsWith(otherInterval);