맴버 변수 란?

맴버 변수는 객체 지향 프로그래밍에서 클래스 내에 선언된 변수를 의미한다.

이는 클래스의 인스턴스(객체)마다 개별적으로 유지되는 데이터를 저장하는데 사용된다.

<aside> 💡

TIP. 클래스의 맴버 변수는 다른 말로 하면 필드(field)다.

</aside>

맴버 변수 유형

맴버 변수는 주로 2가지 유형으로 나뉜다.

인스턴스 변수

클래스의 각 인스턴스에 대해 별도로 존재하는 변수다. 객체가 생성될 때마다 새로운 인스턴스 변수가 생성된다.

class Student {
    // 인스턴스 변수
    private String name;
    private int age;

    // 생성자
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter 메서드
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public static void main(String[] args) {
        Student student1 = new Student("Alice", 20);
        Student student2 = new Student("Bob", 22);

        System.out.println(student1.getName());  // 출력: Alice
        System.out.println(student2.getName());  // 출력: Bob
    }
}

위 코드에서 클래스 Student에 name과 age라는 인스턴스 변수가 있다면.

각 Student 객체는 고유한 name과 age값을 가질 수 있다.

클래스 변수