Java에서 Getter 및 Setter는 데이터를 보호하고 코드를 더욱 안전하게 만드는 데 사용되는 메서드입니다. Getter 및 Setter를 사용하면 프로그래머가 특정 데이터 유형에 대한 값을 설정하고 가져오는 데 편리합니다.
char 및 int 자바
자바의 게터: Getter는 값(접근자)을 반환하고 int, String, double, float 등의 데이터 유형 값을 반환합니다. 프로그램의 편의를 위해 getter는 get이라는 단어로 시작하고 그 뒤에 변수 이름이 옵니다.
Java의 세터: Setter가 값(변경자)을 설정하거나 업데이트하는 동안. 클래스 프로그램에 사용되는 모든 변수의 값을 설정합니다. set이라는 단어로 시작하고 그 뒤에 변수 이름이 옵니다.
통사론
class ABC{ private variable; public void setVariable(int x){ this.variable=x; } public int getVariable{ return variable; } }> 메모: getter와 setter 모두 변수의 첫 글자는 대문자여야 합니다.
Java의 Getter 및 Setter 예
예시 1:
자바
// Java Program to Illustrate Getter and Setter> // Importing input output classes> import> java.io.*;> // Class 1> // Helper class> class> GetSet {> >// Member variable of this class> >private> String name;> >// Method 1 - Getter> >public> String getName() {>return> name; }> >// Method 2 - Setter> >public> void> setName(String N)> >{> >// This keyword refers to current instance itself> >this>.name = N;> >}> }> // Class 2> // Main class> class> GFG {> >// Main driver method> >public> static> void> main(String[] args)> >{> >// Creating an object of class 1 in main() method> >GetSet obj =>new> GetSet();> >// Setting the name by calling setter method> >obj.setName(>'Geeks for Geeks'>);> >// Getting the name by calling getter method> >System.out.println(obj.getName());> >}> }> |
엑셀로 근속기간 계산하기
>
>산출
Geeks for Geeks>
Getter 및 Setter를 사용하면 코드 요구 사항에 따라 모든 데이터 유형의 변수 값을 편리하게 입력할 수 있습니다. Getter 및 Setter를 사용하면 코드의 중요한 변수에 액세스하고 변경하는 방법을 관리할 수 있습니다. 아래에 설명된 프로그램에서 다음과 같이 볼 수 있습니다.
실시예 2
자바
// Java Program to Illustrate Getter and Setter> // Importing input output classes> import> java.io.*;> class> GetSet {> >// Member variable of this class> >private> int> num;> >// Method 1 - Setter> >public> void> setNumber(>int> number)> >{> >// Checking if number is between 1 to 10 exclusive> >if> (number <>1> || number>>10>) {> >throw> new> IllegalArgumentException();> >}> >num = number;> >}> >// Method 2 - Getter> >public> int> getNumber() {>return> num; }> }> // Class 2> // Main class> class> GFG {> >// Main driver method> >public> static> void> main(String[] args)> >{> >GetSet obj =>new> GetSet();> >// Calling method 1 inside main() method> >obj.setNumber(>5>);> >// Printing the number as setter above> >System.out.println(obj.getNumber());> >}> }> |
이런, 자바의 개념
>
>산출
5>
위 프로그램에 대한 설명:
여기서 우리는 10보다 큰 값을 취하면 오류가 표시된다는 것을 알 수 있습니다. setNumber() 메서드를 사용하면 숫자 값이 항상 1에서 10 사이인지 확인할 수 있습니다. 이는 업데이트하는 것보다 훨씬 낫습니다. 숫자 변수를 직접적으로 사용합니다.
메모: 이는 숫자를 개인 변수로 만들고 setNumber 메소드를 활용하여 피할 수 있습니다. 반면에 getter 메서드를 사용하는 것은 숫자 값을 읽는 유일한 방법입니다.