본문 바로가기
자바(Java)/자바 클래스

[Java Class.09]Getters & Setters

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

[Java Class.09]Getters & Setters

 

1. Getters / Accessors

  • 클래스 안에 있는 instance variable(field)은 보통 private으로 선언하기 때문에, 이 intance variable에 접근하게 해주는 메소드(accessor or getter 메소드)를 public으로 만들어 주면 된다.
  • getter 메소드의 return type은 instance variable의 type과 똑같다.

[예제1-1]

1
2
3
4
5
6
7
8
9
10
11
12
class ExampleTemplate
{
 
    // Instance variable declaration
    private typeOfVar varName;
 
    // Accessor (getter) method template
    public typeOfVar getVarName()
    {
        return varName;
    }
}
cs

 

[예제1-2]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Student
{
 
  //Instance variable name
  private String name;
 
  /** getName() example
   *  @return name */
  public String getName()
  {
     return name;
  }
 
  public static void main(String[] args)
  {
     // To call a get method, use objectName.getVarName()
     Student s = new Student();
     System.out.println("Name: " + s.getName() );
  }
cs

 

 

[유제1]

Try the following code. Note that it has a bug! It tries to access the private instance variable email from outside the class Student. Change the main method in Main class so that it uses the appropriate public accessor method (get method) to access the email value instead.

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
38
39
40
41
public class Main {
    // main method for testing
    public static void main(String[] args)
    {
        Student s1 = new Student("Skyler""skyler@sky.com"123456);
        System.out.println("Name:" + s1.getName());
        // Fix the bug here!
        System.out.println("Email:" + s1.email);
        System.out.println("ID: " + s1.id;
    }
}
/** Class Student keeps track of name, email, and id of a Student. */
class Student
{
    private String name;
    private String email;
    private int id;
    public Student(String initName, String initEmail, int initId)
    {
        name = initName;
        email = initEmail;
        id = initId;
    }
    // accessor methods - getters
    /** getName() @return name */
    public String getName()
    {
        return name;
    }
    /** getEmail() @return email */
    public String getEmail()
    {
        return email;
    }
    /** getName() @return id */
    public int getId()
    {
        return id;
    }
}
 
cs

 

 

2. Setters / Mutators

  • 클래스 안에 있는 instance variable의 값을 수정하려면 setter(matator) 메소드를 이용하게끔 코딩해 주면 된다.
  • setter 메소드는 void type으로서 return 값은 없고, 메소드에 parameter를 받아 instance variable을 수정하게 코딩해주면 된다.

 

[예제2-1]

1
2
3
4
5
6
7
8
9
10
11
class ExampleTemplate
{
    // Instance variable declaration
    private typeOfVar varName;
 
    // Setter method template
    public void setVarName(typeOfVar newValue)
    {
        varName = newValue;
    }
}
cs

 

[예제2-1]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Student
{
    // Instance variable name
    private String name;
 
    /**
     * setName sets name to newName
     *
     * @param newName
     */
    public void setName(String newName)
    {
        name = newName;
    }
 
    public static void main(String[] args)
    {
        // To call a set method, use objectName.setVar(newValue)
        Student s = new Student();
        s.setName("Ayanna");
    }
}
cs

 

 

*setter 와 getter 메소드의 차이점
1. getter 메소드는 instance variable값을 리턴한다. 리턴 타입도 instance variable과 똑같다. 메소드에 parameter가 없다.
2. setter 메소드는 리턴하는 값이 없어 void type이다. 메소드에 파라미터가 존재하여, 이 파라미터로 instance variable값을 수정한다.

 

 

*(주의)

getter / setter 메소드는 이름이 반드시 get, set으로 시작하지 않아도 된다. 보통 get, set으로 시작하는 이름으로 많이 지으며, AP시험에서는 혹시 다른 메소드 이름으로 getter / setter 역할을 하는 메소드가 나올 수도 있다.

 

 

[유제2]

Fix the main method to include a call to the appropriate set method.

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class Main {
    // main method for testing
    public static void main(String[] args) {
        Student s1 = new Student("Skyler""skyler@sky.com"123456);
        System.out.println(s1);
        s1.setName("Skyler 2");
        // Main doesn't have access to email, use set method!
        s1.email = "skyler2@gmail.com";
        System.out.println(s1);
    }
}
 
class Student
{
    private String name;
    private String email;
    private int id;
 
    public Student(String initName, String initEmail, int initId)
    {
        name = initName;
        email = initEmail;
        id = initId;
    }
 
    // Setters
 
    public void setName(String newName)
    {
        name = newName;
    }
 
    public void setEmail(String newEmail)
    {
        email = newEmail;
    }
 
    // Getters
 
    public String getName()
    {
        return name;
    }
 
    public String getEmail()
    {
        return email;
    }
 
    public int getId()
    {
        return id;
    }
 
    public String toString()
    {
        return id + ": " + name + ", " + email;
    }
}
cs

 

 

[유제3]

Consider the class Party which keeps track of the number of people at the party.

1
2
3
4
5
6
7
8
9
10
public class Party
{
    // number of people at the party
    private int numOfPeople;
 
    /* Missing header of set method */
    {
        numOfPeople = people;
    }
}
cs

 

Which of the following method signatures could replace the missing header for the set method in the code above so that the method will work as intended?

 

A. public int getNum(int people)

B. public int setNum()

C. public int setNum(int people)

D. public void setNum(int people)

E. public int setNumOfPeople(int p)


 

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

더보기

[유제1 정답]

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
38
39
40
41
public class Main {
    // main method for testing
    public static void main(String[] args)
    {
        Student s1 = new Student("Skyler""skyler@sky.com"123456);
        System.out.println("Name:" + s1.getName());
        // Fix the bug here!
        System.out.println("Email:" + s1.getEmail());
        System.out.println("ID: " + s1.getId());
    }
}
/** Class Student keeps track of name, email, and id of a Student. */
class Student
{
    private String name;
    private String email;
    private int id;
    public Student(String initName, String initEmail, int initId)
    {
        name = initName;
        email = initEmail;
        id = initId;
    }
    // accessor methods - getters
    /** getName() @return name */
    public String getName()
    {
        return name;
    }
    /** getEmail() @return email */
    public String getEmail()
    {
        return email;
    }
    /** getName() @return id */
    public int getId()
    {
        return id;
    }
}
 
cs

 

[유제2 정답]

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class Main {
    // main method for testing
    public static void main(String[] args) {
        Student s1 = new Student("Skyler""skyler@sky.com"123456);
        System.out.println(s1);
        s1.setName("Skyler 2");
        // Main doesn't have access to email, use set method!
        s1.setEmail("skyler2@gmail.com");
        System.out.println(s1);
    }
}
 
class Student
{
    private String name;
    private String email;
    private int id;
 
    public Student(String initName, String initEmail, int initId)
    {
        name = initName;
        email = initEmail;
        id = initId;
    }
 
    // Setters
 
    public void setName(String newName)
    {
        name = newName;
    }
 
    public void setEmail(String newEmail)
    {
        email = newEmail;
    }
 
    // Getters
 
    public String getName()
    {
        return name;
    }
 
    public String getEmail()
    {
        return email;
    }
 
    public int getId()
    {
        return id;
    }
 
    public String toString()
    {
        return id + ": " + name + ", " + email;
    }
}
cs

 

[유제3 정답]

D

(the set method should take a parameter called people and have a void return value. The name of the set method is usually set followed by the full instance variable name, but it does not have to be an exact match)

728x90
반응형

댓글