java-variable-scope
Javaの変数スコープ
1. 概要
Javaでは、プログラミング言語と同様に、各変数にはスコープがあります。 これは、変数を使用できる有効なプログラムのセグメントです。
このチュートリアルでは、Javaで利用可能なスコープを紹介し、それらの違いについて説明します。
2. クラススコープ
クラスの角かっこ(_ \ {} _)内で_private_ access修飾子を使用して宣言されているが、メソッドの外部にある各変数には、scopeスコープがあります。 その結果、*これらの変数はクラス内のどこでも使用できますが、外部では使用できません*:
public class ClassScopeExample {
private Integer amount = 0;
public void exampleMethod() {
amount++;
}
public void anotherExampleMethod() {
Integer anotherAmount = amount + 4;
}
}
_ClassScopeExample_には、クラスのメソッド内でアクセスできるクラス変数_amount_があることがわかります。
_private_を使用しない場合、パッケージ全体からアクセスできます。 詳細については、https://www.baeldung.com/java-access-modifiers [アクセス修飾子の記事]を確認してください。
3. メソッドの範囲
メソッド内で変数が宣言されると、method scopeを持ち、**同じメソッド内でのみ有効になります:**
public class MethodScopeExample {
public void methodA() {
Integer area = 2;
}
public void methodB() {
// compiler error, area cannot be resolved to a variable
area = area + 2;
}
}
_methodA_で、_area_というメソッド変数を作成しました。 そのため、_methodA_内で_area_を使用できますが、他の場所では使用できません。
4. ループスコープ
ループ内で変数を宣言すると、変数はループスコープを持ち、**ループ内でのみ使用可能になります:**
public class LoopScopeExample {
List<String> listOfNames = Arrays.asList("Joe", "Susan", "Pattrick");
public void iterationOfNames() {
String allNames = "";
for (String name : listOfNames) {
allNames = allNames + " " + name;
}
// compiler error, name cannot be resolved to a variable
String lastNameUsed = name;
}
}
メソッド_iterationOfNames_には_name_というメソッド変数があることがわかります。 この変数はループ内でのみ使用でき、ループ外では無効です。
5. ブラケットスコープ
*角かっこを使用して、どこでも追加のスコープを定義できます*(_ \ {} _):
public class BracketScopeExample {
public void mathOperationExample() {
Integer sum = 0;
{
Integer number = 2;
sum = sum + number;
}
// compiler error, number cannot be solved as a variable
number++;
}
}
変数_number_は、括弧内でのみ有効です。
6. スコープと変数シャドウイング
クラス変数があり、同じ名前のメソッド変数を宣言するとします。
public class NestedScopesExample {
String title = "Baeldung";
public void printTitle() {
System.out.println(title);
String title = "John Doe";
System.out.println(title);
}
}
初めてタイトルを印刷するときは、「Baeldung」と印刷されます。 その後、同じ名前のメソッド変数を宣言し、それに値「John Doe___」を割り当てます。
titleメソッド変数は、_class_変数_title_に再度アクセスする可能性をオーバーライドします。 そのため、2回目は「John Doe__」を出力します。
*混乱するでしょう? これは_variable shadowing_ *と呼ばれ、良い習慣ではありません。 _this.title_のような_title_クラス変数にアクセスするには、接頭辞__this __inを使用することをお勧めします。
7. 結論
Javaに存在するさまざまなスコープを学びました。
いつものように、コードはhttps://github.com/eugenp/tutorials/tree/master/core-java-modules/core-java-lang[GitHub]で入手できます。