Using a non-static method without referring it to an object?

Go To StackoverFlow.com

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*/}
}

My question lies with the return getTime().overlapsWith(other.getTime()) statement.getTime() is not a static method, so I think it can only be used when it is referring to an object. But from that statement, no object is being referred to. I understand that getTime() returns an object for the subsequent methods but what about itself? My classmate offers an explanation stating that "when we want to use the conflictsWith() method, we would declare an object, thus the return statement would be equivalent to return object.getTime().overlapsWith(other.getTime());" Is this explanation correct? So does that mean when we use a non-static method inside a method, no object is needed to be referred to?

2012-04-05 02:10
by Adlius


6

Since getTime() is not a static method, it's invoked on the current object. The implementation is equivalent to

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

You'd only invoke conflictsWith() on an Appointment object, like this:

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-05 02:13
by Adam Liss


2

When calling a non-static method, the object this is implied. At runtime the this object refers to the instance of the object that is being operated on. In your case, it refers to the object for which the outer method was called.

2012-04-05 02:12
by Jeremy
Thank you jeremy, but I have more questions: 1.Does that mean I could neglect using an object when I am using a method inside a method? 2. what is 'this' referred to? A hidden object of this class? I am sorry if these are really simple - Adlius 2012-04-05 02:18
this is a keyword, which acts as an object reference, and which refers to the object instance you are in - QuantumMechanic 2012-04-05 02:21


0

Inside Appointment, getTime() is equivalent to this.getTime().

Your conflictsWith could be rewritten that way:

TimeInterval thisInterval = this.getTime(); // equivalent to just getTime()
TimeInterval otherInterval = object.getTime();
return thisInterval.overlapsWith(otherInterval);
2012-04-05 02:20
by ptyx
Ads