JAVA에서 Getter와 Setter

임유빈·2023년 11월 7일

개발자

목록 보기
21/26

Getter(get메소드)

Getter메소드는 클래스의 맴버 변수의 값을 읽어오는 메소드이다.
주로 'getVariableName()'와 같은 형태로 작성된다. VariableName-> 변수 이름
ex)

public class MyClass {
    private int myVariable;
    
    public int getMyVariable() {
        return myVariable;
    }
}

Setter(set메소드)

Setter 메소드는 클래스의 맴버 변수에 값을 설정하는 메소드이다.
주로 'setBariableName(value)'와 같은 형태로 작성된다. VariableName-> 변수 이름
ex)

public class MyClass {
    private int myVariable;
    
    public void setMyVariable(int value) {
        if (value >= 0) {
            myVariable = value;
        } else {
            System.out.println("유효하지 않은 값입니다.");
        }
    }
}
profile
주변 사람들과의 소통을 적극적으로 하는 친근한 개발자가 되기를 희망합니다.

0개의 댓글