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?
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
}
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.
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
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);