クラスまたはコンストラクターで、studentName と studentAverage の使用はどのように異なりますか?
public class StackOverFlowQ {
String studentName;
int studentAverage;
public void StackOverFlowQ (String stedentName, int studentAverage){
}
}
クラスまたはコンストラクターで、studentName と studentAverage の使用はどのように異なりますか?
public class StackOverFlowQ {
String studentName;
int studentAverage;
public void StackOverFlowQ (String stedentName, int studentAverage){
}
}
これはシャドウイングと呼ばれ、この状況に当てはまる特定のケースがあります。
n という名前のフィールドまたは仮パラメーターの宣言 d は、d のスコープ全体で、d が発生した時点でスコープ内にある n という名前の他の変数の宣言をシャドウします。
あなたのためにそれを少し蒸留するには:
コンストラクターでフィールドstudentName
とstudentAverage
仮パラメーターを宣言しました。 そのコンストラクターのスコープでは、上記の 2 つの名前への参照はパラメーターを使用するものとして扱われ、他の上位レベルのフィールドは扱われません。
this
フィールドを参照する必要がある場合は、フィールドを逆参照しているかのようにキーワードを使用します。
this.studentName = studentName;
this.studentAverage = studentAverage;
変数のシャドウイングだけでなく、アクセスにも使用方法に大きな違いがあります。コンストラクターでは、変数のみを持ち、そのスコープ内で使用できますstudentName
。studentAverage
このクラスをインスタンス化する人は、フィールドに取り込まれない限り、これらのパラメーターの値にアクセスできません。
したがって、同様の名前のフィールドが機能します。これらのフィールドは、他のメソッドによる可視性または公開に応じて、実際には他のクラスで使用できます。
コンストラクターで、インスタンス変数を参照する場合は、先頭にthis
;を付ける必要があります。そうしないと、パラメーターを参照することになります。
例えば:
public class StackOverFlowQ {
String studentName;
int studentAverage;
public StackOverFlowQ (String studentName, int studentAverage){
this.studentName = "Paul" // will point to the instance variable.
studentName = "Paul"; // will point to the parameter in the constructor
}
}