2012-04-05 28 views
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());と等しくなります」と説明しています。「この説明は正しいですか?つまり、メソッド内で非静的メソッドを使用すると、オブジェクトを参照する必要はありません。オブジェクトを参照せず非静的メソッドを使用していますか?

答えて

2

非静的メソッドを呼び出すときは、オブジェクトthisが暗黙指定されています。実行時にthisオブジェクトは、操作対象のオブジェクトのインスタンスを参照します。あなたの場合は、外部メソッドが呼び出されたオブジェクトを参照します。

+0

はあなたのジェレミーありがとう、私は多くの質問があります:私は、メソッドの内部でメソッドを使用していたとき、私は、オブジェクトを使用して無視でき意味1.Doesを? 2.「これ」とは何ですか?このクラスの隠されたオブジェクト?これらが本当にシンプルなのは残念です。 – Adlius

+0

'this'はキーワードです。これはオブジェクト参照として機能し、現在のオブジェクトインスタンスを参照します。 – QuantumMechanic

6

getTime()は静的メソッドではないため、現在のオブジェクトに対して呼び出されます。実装はあなたがこれだけのように、AppointmentオブジェクトにconflictsWith()を呼び出すと思います

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

と同等です:予定インサイド

Appointment myAppt = new Appointment(); 
Appointment otherAppt = new Appointment(); 
// Set the date of each appt here, then check for conflicts 
if (myAppt.conflictsWith(otherAppt)) { 
    // Conflict 
} 
0

、getTime())は、(this.getTimeと同等です。

あなたconflictsWithがそのように書き換えることができます

TimeInterval thisInterval = this.getTime(); // equivalent to just getTime() 
TimeInterval otherInterval = object.getTime(); 
return thisInterval.overlapsWith(otherInterval); 
関連する問題