본문 바로가기
자바(Java)/자바기초

[자바기초.027] 변수 사용 범위(Scope & Access)

by 긱펀 2024. 3. 26.
반응형

[자바기초.027] 변수 사용 범위(Scope & Access)

 

1. 변수의 사용 범위

자바에서 변수를 만들 때, 변수의 사용 범위는 { } 로 정해진다. 자바에는 3가지 변수 범위(level of scope)가 있다.

  • Class Level Scope for instance variables inside a class.
  • Method Level Scope for local variables (including parameter variables) inside a method.
  • Block Level Scope for loop variables and other local variables defined inside of blocks of code with { }.

 

 

  • 지역 변수(Local variables)는 method 안에서 만들어진 변수로서, 사용 범위도 method 안으로 한정된다. method 밖에서 지역 변수는 존재하지 않게 된다.(그래서 사용범위 밖에서 변수를 사용하면 error가 발생한다.)
  • 매개 변수(Parameter)도 역시 지역 변수이다.
  • Class Scope의 범위를 가지는 Instance variable은 그 클래스 안에 있는 모든 method가 공유하는 변수이다. Instance variable을 public으로 하면 그 클래스 밖에서도 직접 변수에 접근가능하고, private으로 하면 그 클래스 밖에서 직접 변수에 접근이 불가능하다.

 

[예제1]

만약 local variable과 instance variable의 변수명이 같다면, 아래 코드의 24번줄에서 name변수는 local variable이 우선시 된다. 그래서 이런식으로 변수명이 헷갈릴 때는 instance variable에 this 키워드를 붙여 써주는 게 좋다.(this 키워드를 붙이면 이 변수가 좀 더 object's instance variable이라는게 확실이 눈으로 구별이 된다.)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Main {
    public static void main(String[] args) {
      // call the constructor to create a new person
      Person p1 = new Person("Sana""sana@gmail.com");
      System.out.println(p1); // unknown: sana@gmail.com
    }
}
 
class Person{
    private String name;
    private String email;
 
    public Person(String initName, String initEmail)
    {
        name = initName;
        email = initEmail;
    }
 
    public String toString()
    {
        String name = "unknown";
        // The local variable name here will be used,
        //  not the instance variable name.
        return name + ": " + email;
    }
}
cs

 

 

[유제1] 아래 코드에서, Class Level Scope의 변수는 무엇인지 변수명과 라인 번호를 함께 말해보세요.

1
2
3
4
5
6
7
8
9
10
11
12
public class Name
{
    private String first;
    public String last;
 
    public Name(String theFirst, String theLast)
    {
        String firstName = theFirst;
        first = firstName;
        last = theLast;
    }
}
cs

 

 

[유제2] 아래 코드에서 Method Level Scope 의 변수는 무엇인지 변수명과 라인 번호를 함께 말해보세요.

1
2
3
4
5
6
7
8
9
10
11
12
public class Name
{
    private String first;
    public String last;
 
    public Name(String theFirst, String theLast)
    {
        String firstName = theFirst;
        first = firstName;
        last = theLast;
    }
}
cs

 

 

[유제3]

아래 코드에서 잘못 사용된 변수 접근을 찾고, 코드를 수정해 보세요.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Person
{
    private String name;
    private String email;
 
    public Person(String initName, String initEmail)
    {
        name = initName;
        email = initEmail;
    }
 
    public String toString()
    {
        for (int i = 0; i < 5; i++)
        {
            int id = i;
        }
        // Can you access the blockScope variables i or id?
        System.out.println("i at the end of the loop is " + i);
        System.out.println("The last id is " + id);
 
        // Can toString() access parameter variables in Person()?
        return initName + ": " + initEmail;
    }
 
    // main method for testing
    public static void main(String[] args)
    {
        // call the constructor to create a new person
        Person p1 = new Person("Sana""sana@gmail.com");
        System.out.println(p1);
    }
}
cs

 

 

 

 


 

[유제 정답은 아래 "더보기" 클릭]

더보기

[유제1 정답]

3번 라인 private String first

4번 라인 public String last

 

[유제2 정답]

6번 라인 String theFirst, String theLast

8번 라인 String firstName

 

[유제3]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Person
{
    private String name;
    private String email;
 
    public Person(String initName, String initEmail)
    {
        name = initName;
        email = initEmail;
    }
 
    public String toString()
    {
        int i = 0;
        int id = 0;
        for ( ; i < 5; i++)
        {
            id = i;
        }
        // Can you access the blockScope variables i or id?
        System.out.println("i at the end of the loop is " + i);
        System.out.println("The last id is " + id);
 
        // Can toString() access parameter variables in Person()?
        return name + ": " + email;
    }
 
    // main method for testing
    public static void main(String[] args)
    {
        // call the constructor to create a new person
        Person p1 = new Person("Sana""sana@gmail.com");
        System.out.println(p1);
    }
}
 
 
cs
728x90
반응형

댓글